package com.ncmmall.application.business.order;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.ncmmall.application.business.distribution.DistributionSettingApplication;
import com.ncmmall.application.business.goods.GoodsApplication;
import com.ncmmall.application.msm.AliYunSmsService;
import com.feijin.commons.exceptions.InterfaceException;
import com.feijin.commons.lang.ArithUtils;
import com.feijin.commons.lang.PropertiesHelps;
import com.feijin.commons.lang.Requires;
import com.feijin.commons.webs.SyncLock;
import com.ncmmall.domain.business.cloudstore.CloudStoreGoods;
import com.ncmmall.domain.business.cloudstore.CloudStoreGoodsRepository;
import com.ncmmall.domain.business.cloudstore.QCloudStoreGoods;
import com.ncmmall.domain.business.distribution.DistributionCheck;
import com.ncmmall.domain.business.distribution.DistributionCheckRepository;
import com.ncmmall.domain.business.distribution.DistributionGoods;
import com.ncmmall.domain.business.distribution.DistributionOrder;
import com.ncmmall.domain.business.distribution.DistributionOrderRepository;
import com.ncmmall.domain.business.distribution.DistributionSetting;
import com.ncmmall.domain.business.distribution.Distributor;
import com.ncmmall.domain.business.distribution.DistributorLevel;
import com.ncmmall.domain.business.distribution.DistributorRepository;
import com.ncmmall.domain.business.distribution.QDistributionOrder;
import com.ncmmall.domain.business.distribution.QDistributor;
import com.ncmmall.domain.business.distribution.QDistributorLevel;
import com.ncmmall.domain.business.express.Express;
import com.ncmmall.domain.business.express.QExpress;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.goods.GoodsRepository;
import com.ncmmall.domain.business.goods.QGoods;
import com.ncmmall.domain.business.goods.attribute.GoodsAttribute;
import com.ncmmall.domain.business.goods.attribute.GoodsAttributeRepository;
import com.ncmmall.domain.business.goods.attribute.GoodsSaleAttribute;
import com.ncmmall.domain.business.goods.attribute.GoodsSaleAttributeRepository;
import com.ncmmall.domain.business.goods.attribute.QGoodsAttribute;
import com.ncmmall.domain.business.goods.comment.GoodsComment;
import com.ncmmall.domain.business.goods.comment.GoodsCommentImage;
import com.ncmmall.domain.business.goods.comment.GoodsCommentImageRepository;
import com.ncmmall.domain.business.goods.comment.GoodsCommentRepository;
import com.ncmmall.domain.business.goods.image.GoodsImage;
import com.ncmmall.domain.business.goods.image.GoodsImageRepository;
import com.ncmmall.domain.business.goods.sku.GoodsSku;
import com.ncmmall.domain.business.goods.sku.GoodsSkuRepository;
import com.ncmmall.domain.business.goods.sku.QGoodsSku;
import com.ncmmall.domain.business.goods.unit.GoodsUnit;
import com.ncmmall.domain.business.goods.unit.QGoodsUnit;
import com.ncmmall.domain.business.live.LiveBalanceRecord;
import com.ncmmall.domain.business.live.LiveBalanceRecordRepository;
import com.ncmmall.domain.business.live.LiveGoods;
import com.ncmmall.domain.business.live.LiveGoodsAnchor;
import com.ncmmall.domain.business.live.LiveOrder;
import com.ncmmall.domain.business.live.LiveOrderRepository;
import com.ncmmall.domain.business.live.LiveSession;
import com.ncmmall.domain.business.live.LiveSetting;
import com.ncmmall.domain.business.live.QLiveGoodsAnchor;
import com.ncmmall.domain.business.live.QLiveOrder;
import com.ncmmall.domain.business.marketing.coupon.Coupon;
import com.ncmmall.domain.business.marketing.coupon.CouponMemberDraw;
import com.ncmmall.domain.business.marketing.coupon.CouponMemberDrawRepository;
import com.ncmmall.domain.business.marketing.coupon.QCoupon;
import com.ncmmall.domain.business.marketing.coupon.QCouponMemberDraw;
import com.ncmmall.domain.business.marketing.gift.GiftActivity;
import com.ncmmall.domain.business.marketing.gift.QGiftActivity;
import com.ncmmall.domain.business.marketing.shoppingcard.QShoppingCardGoods;
import com.ncmmall.domain.business.marketing.shoppingcard.QShoppingCardMerchant;
import com.ncmmall.domain.business.marketing.shoppingcard.QShoppingCardRecord;
import com.ncmmall.domain.business.marketing.shoppingcard.QShoppingCardRecordConsume;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCard;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCardGoods;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCardMerchant;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCardRecord;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCardRecordConsume;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCardRecordConsumeRepository;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCardRecordRepository;
import com.ncmmall.domain.business.merchant.freight.MerchantFreight;
import com.ncmmall.domain.business.merchant.freight.MerchantFreightTemplate;
import com.ncmmall.domain.business.merchant.freight.QMerchantFreight;
import com.ncmmall.domain.business.merchant.freight.QMerchantFreightTemplate;
import com.ncmmall.domain.business.message.Message;
import com.ncmmall.domain.business.message.MessageRepository;
import com.ncmmall.domain.business.order.Order;
import com.ncmmall.domain.business.order.OrderDetail;
import com.ncmmall.domain.business.order.OrderDetailRepository;
import com.ncmmall.domain.business.order.OrderRepository;
import com.ncmmall.domain.business.order.QOrder;
import com.ncmmall.domain.business.order.QOrderDetail;
import com.ncmmall.domain.business.order.delivery.SupplierOrderDelivery;
import com.ncmmall.domain.business.order.delivery.SupplierOrderDeliveryDetail;
import com.ncmmall.domain.business.order.delivery.SupplierOrderDeliveryDetailRepository;
import com.ncmmall.domain.business.order.delivery.SupplierOrderDeliveryRepository;
import com.ncmmall.domain.business.order.dto.CouponDTO;
import com.ncmmall.domain.business.order.dto.GiftActivityDTO;
import com.ncmmall.domain.business.order.dto.OrderDTO;
import com.ncmmall.domain.business.order.dto.OrderDetailDTO;
import com.ncmmall.domain.business.order.dto.ShoppingCardRecordDTO;
import com.ncmmall.domain.business.order.groupbooking.GroupBooking;
import com.ncmmall.domain.business.order.groupbooking.GroupBookingOrder;
import com.ncmmall.domain.business.order.groupbooking.GroupBookingOrderRepository;
import com.ncmmall.domain.business.order.groupbooking.GroupBookingRepository;
import com.ncmmall.domain.business.order.groupbooking.QGroupBooking;
import com.ncmmall.domain.business.order.groupbooking.QGroupBookingOrder;
import com.ncmmall.domain.business.order.lading.BillOfLading;
import com.ncmmall.domain.business.order.lading.BillOfLadingRepository;
import com.ncmmall.domain.business.order.lading.QBillOfLading;
import com.ncmmall.domain.business.shoppingcart.QShoppingCart;
import com.ncmmall.domain.business.shoppingcart.ShoppingCart;
import com.ncmmall.domain.business.shoppingcart.ShoppingCartRepository;
import com.ncmmall.domain.business.trading.TradingLog;
import com.ncmmall.domain.business.trading.TradingLogRepository;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.domain.security.user.WebUserRepository;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 订单业务
 *
 * @author linxs
 * @date 2019-07-16 11:19
 */
@Service
@Transactional
@Slf4j
public class OrderApplication {

    @Autowired
    private GoodsApplication goodsApplication;
    @Autowired
    private GoodsImageRepository imageRepository;
    @Autowired
    private GoodsSaleAttributeRepository saleAttributeRepository;
    @Autowired
    private GoodsAttributeRepository attributeRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private OrderDetailRepository detailRepository;
    @Autowired
    private WebUserRepository userRepository;
    @Autowired
    private GoodsCommentImageRepository commentImageRepository;
    @Autowired
    private GoodsCommentRepository commentRepository;
    @Autowired
    private ShoppingCartRepository cartRepository;
    @Autowired
    private GoodsSkuRepository skuRepository;
    @Autowired
    private GoodsRepository goodsRepository;
    @Autowired
    private QueryChannelService queryChannelService;
    @Autowired
    private MessageRepository messageRepository;
    @Autowired
    private TradingLogRepository tradingLogRepository;
    @Autowired
    private CouponMemberDrawRepository memberDrawRepository;
    @Autowired
    private ShoppingCardRecordRepository shoppingCardRecordRepository;
    @Autowired
    private ShoppingCardRecordConsumeRepository shoppingCardRecordConsumeRepository;
    @Autowired
    private GroupBookingRepository groupBookingRepository;
    @Autowired
    private GroupBookingOrderRepository groupBookingOrderRepository;
    @Autowired
    private SupplierOrderDeliveryRepository deliveryRepository;
    @Autowired
    private SupplierOrderDeliveryDetailRepository deliveryDetailRepository;
    @Autowired
    private CloudStoreGoodsRepository cloudStoreRepository;
    @Autowired
    private BillLadingApplication billLadingApplication;
    @Autowired
    private BillOfLadingRepository billOfLadingRepository;
    @Autowired
    private DistributionCheckRepository distributionCheckRepository;
    @Autowired
    private DistributionSettingApplication distributionSettingApplication;
    @Autowired
    private DistributionOrderRepository distributionOrderRepository;
    @Autowired
    private DistributorRepository distributorRepository;
    @Autowired
    private LiveOrderRepository liveOrderRepository;
    @Autowired
    private LiveBalanceRecordRepository liveBalanceRecordRepository;

    /**
     * 提交订单
     */
    public List<Order> submitOfSupplier(WebUser member, OrderDTO orderDTO) {

        List<Order> orders = new ArrayList<>();
        Set<Long> merchantIds = new HashSet<>();

        for (OrderDetailDTO skuParams : orderDTO.getDetails()) {
            GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(skuParams.getId()), GoodsSku.class);
            merchantIds.add(sku.getMerchant().getId());
        }

        List<WebUser> merchants = queryChannelService.findAll(QWebUser.webUser.id.in(merchantIds), WebUser.class);

        for (WebUser merchant : merchants) {
            Order order = new Order();
            order.setIsSupplier(1);
            order.setMember(member);
            order.setMerchant(merchant);
            order.setCreateTime(new Timestamp(System.currentTimeMillis()));
            order.setDeliveryName(orderDTO.getDeliveryName());
            order.setDeliveryProvince(orderDTO.getDeliveryProvince());
            order.setDeliveryCity(orderDTO.getDeliveryCity());
            order.setDeliveryArea(orderDTO.getDeliveryArea());
            order.setDeliveryAddress(orderDTO.getDeliveryAddress());
            order.setDeliveryMobile(orderDTO.getDeliveryMobile());
            order.setShippingMethod(orderDTO.getShippingMethod());

            order.setSupplierBankCardNo(order.getMerchant().getBankCardNo());
            order.setSupplierBankName(order.getMerchant().getBankName() + order.getMerchant().getBankSubBranchName());
            order.setSupplierBankAccountHolder(order.getMerchant().getBankAccountHolder());

            String orderNo = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + merchant.getId() + member.getId();
            order.setOrderNo(orderNo);

            order.setStatus(1);
            order.setPayStatus(2);

            order.setInvoiceTFN(orderDTO.getInvoiceTFN());
            order.setInvoiceTitle(orderDTO.getInvoiceTitle());
            order.setHaveInvoice(orderDTO.getHaveInvoice());
            order.setInvoiceTitleType(orderDTO.getInvoiceTitleType());
            order.setInvoiceType(orderDTO.getInvoiceType());

            orderRepository.save(order);

            double freightPrice = 0;
            double goodsSubtotalPrice = 0;
            int quantity = 0;

            List<Goods> result = Lists.newArrayList();
            Map<Long, Integer> numbers = Maps.newHashMap();
            Map<Long, Double> grams = Maps.newHashMap();

            //订单详情
            for (OrderDetailDTO skuParams : orderDTO.getDetails()) {

                order.setDeliveryType(skuParams.getDeliveryType());
                order.setNote(skuParams.getNote());
                orderRepository.save(order);

                GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(skuParams.getId()), GoodsSku.class);

                double price = 0;

                if (sku.getMerchant().getId() == merchant.getId()) {

                    if (skuParams.getDeliveryType() == 1) {
                        price = ArithUtils.mul(goodsApplication.getSupplierLeverPrice(sku, skuParams.getQuantity()), skuParams.getQuantity());     //单价 * 数量

                    } else if (skuParams.getDeliveryType() == 2) {
                        price = ArithUtils.mul(goodsApplication.getSupplierLeverPrice(sku, skuParams.getQuantity()), skuParams.getQuantity());     //单价 * 数量
                    }


                    if (price < 0) {
                        price = 0;
                    }


                    OrderDetail detail = new OrderDetail();

                    detail.setSku(sku);
                    detail.setProductNo(sku.getGoods().getGoodsNo());
                    detail.setDefaultImage(sku.getGoods().getDefaultImage());
                    detail.setGoodsName(sku.getGoods().getName());
                    detail.setSpecs(sku.getAttribute1().getName() + " " + (null != sku.getAttribute2() ? sku.getAttribute2().getName() : ""));
                    detail.setQuantity(skuParams.getQuantity());
                    detail.setPrice(price);
                    detail.setOrder(order);
                    detail.setUnitPrice(goodsApplication.getSupplierLeverPrice(sku, skuParams.getQuantity()));

                    detail.setUnit(queryChannelService.findOne(QGoodsUnit.goodsUnit.id.eq(skuParams.getUnitId()), GoodsUnit.class));
                    detail.setUnitquantity(skuParams.getUnitQuantity());

                    detail.setDeliveryType(skuParams.getDeliveryType());
                    detail.setDeliveryQuantity(skuParams.getDeliveryQuantity());

                    detailRepository.save(detail);
                    goodsSubtotalPrice = ArithUtils.add(goodsSubtotalPrice, price);
                    quantity = quantity + skuParams.getQuantity();

                    ShoppingCart cart = queryChannelService.findOne(QShoppingCart.shoppingCart.member.eq(order.getMember()).and(QShoppingCart.shoppingCart.sku.eq(sku)), ShoppingCart.class);
                    if (null != cart) {
                        cartRepository.delete(cart);
                    }

                    Goods goods = sku.getGoods();


                    if (skuParams.getDeliveryType() == 2) {
                        skuParams.setQuantity(skuParams.getDeliveryQuantity());
                    }


                    if (numbers.containsKey(goods.getId())) {
                        int count = numbers.get(goods.getId());
                        double gram = grams.get(goods.getId());
                        numbers.put(goods.getId(), count + skuParams.getQuantity());
                        grams.put(goods.getId(), gram + goods.getGram());

                    } else {

                        numbers.put(goods.getId(), skuParams.getQuantity());
                        grams.put(goods.getId(), goods.getGram());
                        result.add(goods);
                    }

                }

            }

            for (Goods goods : result) {
                int count = numbers.get(goods.getId());
                double gramCount = grams.get(goods.getId());

                //运费计算逻辑
                if (count != 0) {
                    if (goods.getSupplierPostageType() == 1) {     //走运费模板

                        MerchantFreight freight = queryChannelService.findOne(QMerchantFreight.merchantFreight.city.eq(order.getDeliveryCity()).and(QMerchantFreight.merchantFreight.merchant.eq(merchant).and(QMerchantFreight.merchantFreight.template.id.eq(goods.getSupplierFreightTemplate().getId()))), MerchantFreight.class);

                        MerchantFreightTemplate template = queryChannelService.findOne(QMerchantFreightTemplate.merchantFreightTemplate.id.eq(goods.getSupplierFreightTemplate().getId()), MerchantFreightTemplate.class);

                        //按重量
                        if (template.getType() == 1) {

                            double gram = ArithUtils.mul(gramCount, count);
                            if (null != freight) {
                                if (gram <= freight.getFirstWeight()) {
                                    freightPrice += freight.getFirstWeightAmount();
                                } else {
                                    double fistWeightAmount = freight.getFirstWeightAmount();
                                    double weight = ArithUtils.sub(gram, freight.getFirstWeight());

                                    if (weight < freight.getOtherWeight()) {
                                        freightPrice += ArithUtils.add(fistWeightAmount, freight.getOtherWeightAmount());
                                    } else {
                                        freightPrice += ArithUtils.add(fistWeightAmount, ArithUtils.mul(Math.ceil(ArithUtils.div(weight, freight.getOtherWeight(), 2)), freight.getOtherWeightAmount()));
                                    }
                                }

                            } else {

                                if (gram <= template.getDefaultWeight()) {
                                    freightPrice += template.getDefaultWeightAmount();
                                } else {

                                    double fistWeightAmount = template.getDefaultWeightAmount();
                                    double weight = ArithUtils.sub(gram, template.getDefaultWeight());

                                    if (weight < template.getDefaultAddWeight()) {
                                        freightPrice += ArithUtils.add(fistWeightAmount, template.getDefaultAddWeightAmount());
                                    } else {
                                        freightPrice += ArithUtils.add(fistWeightAmount, ArithUtils.mul(Math.ceil(ArithUtils.div(weight, template.getDefaultAddWeight(), 2)), template.getDefaultAddWeightAmount()));
                                    }
                                }

                            }

                        }


                        //按件
                        if (template.getType() == 2) {

                            if (null != freight) {

                                if (count <= freight.getFirstPiece()) {
                                    freightPrice += freight.getFirstPieceAmount();
                                } else {
                                    freightPrice += ArithUtils.add(freight.getFirstPieceAmount(), ArithUtils.mul(ArithUtils.sub(count, freight.getFirstPiece()), freight.getOtherPieceAmount()));
                                }

                            } else {

                                if (count <= template.getDefaultPiece()) {
                                    freightPrice += template.getDefaultPieceAmount();
                                } else {
                                    freightPrice += ArithUtils.add(template.getDefaultPieceAmount(), ArithUtils.mul(ArithUtils.sub(count, template.getDefaultPiece()), template.getDefaultAddPieceAmount()));
                                }

                            }

                        }

                    } else if (goods.getSupplierPostageType() == 2) {      //包邮
                        freightPrice += ArithUtils.add(freightPrice, 0);
                    } else if (goods.getSupplierPostageType() == 3) {       //指定运费
                        freightPrice += ArithUtils.add(freightPrice, ArithUtils.mul(goods.getSupplierPostage(), count));
                    }

                }


            }


            if (order.getShippingMethod() == 2) {
                freightPrice = 0;
                order.setShippingAddress(order.getMerchant().getWarehouseAddress());
            }

            double totalPrice = ArithUtils.add(freightPrice, goodsSubtotalPrice);

            order.setFreightPrice(freightPrice);
            order.setGoodsSubtotalPrice(goodsSubtotalPrice);
            order.setPrice(totalPrice);
            order.setMoney(totalPrice);
            order.setGoodsQuantity(quantity);
            LocalDateTime dateTime = LocalDateTime.now().plusHours(1);
            order.setAutoCancelTime(Timestamp.valueOf(dateTime));


            orderRepository.save(order);

            List<OrderDetail> orderDetails = queryChannelService.findAll(QOrderDetail.orderDetail.order.id.eq(order.getId()), OrderDetail.class);

            //减库存，加销量
            for (OrderDetail detail : orderDetails) {
                GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.eq(detail.getSku()), GoodsSku.class);
                Goods goods = queryChannelService.findOne(QGoods.goods.eq(sku.getGoods()), Goods.class);
                sku.setStore(Math.max((sku.getStore() - detail.getQuantity()), 0));
                skuRepository.save(sku);

                goods.setStore(Math.max((goods.getStore() - detail.getQuantity()), 0));
                goods.setSalesVolume(goods.getSalesVolume() + detail.getQuantity());

                if (goods.getStore() == 0) {
                    goods.setStatus(6);
                }

                goodsRepository.save(goods);
            }
            orders.add(order);
        }

        return orders;
    }

    /**
     * 判断当前商品是否可以使用购物卡
     *
     * @param record 购物卡
     * @param sku    sku
     * @return true 可以 false 不可以
     */
    private boolean havaUseRecord(ShoppingCardRecord record, GoodsSku sku) {

        ShoppingCard card = record.getShoppingCard();
        if (card.getAreaType() == 1 && card.getGoodsType() == 1 && card.getMerchantType() == 1) {
            return true;
        }

        boolean flag = false;
        if (card.getMerchantType() == 2) {
            //指定商家可以使用
            List<ShoppingCardMerchant> list = queryChannelService.findAll(QShoppingCardMerchant.shoppingCardMerchant.shoppingCard.id.eq(card.getId()), ShoppingCardMerchant.class);
            for (ShoppingCardMerchant shoppingCardMerchant : list) {
                if (sku.getMerchant().getId() == shoppingCardMerchant.getMerchant().getId()) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                return false;
            }
            flag = false;
        }

        if (card.getGoodsType() == 2) {
            //指定商品可以使用
            List<ShoppingCardGoods> list = queryChannelService.findAll(QShoppingCardGoods.shoppingCardGoods.shoppingCard.id.eq(card.getId()), ShoppingCardGoods.class);
            for (ShoppingCardGoods shoppingCardGoods : list) {
                if (sku.getGoods().getId() == shoppingCardGoods.getGoods().getId()) {
                    flag = true;
                    break;
                }
            }
            return flag;
        }

        return true;
    }

    /**
     * 提交订单
     */
    public List<Order> submit(WebUser member, OrderDTO orderDTO) {

        List<Order> orders = new ArrayList<>();
        Set<Long> merchantIds = new HashSet<>();

        for (OrderDetailDTO skuParams : orderDTO.getDetails()) {
            GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(skuParams.getId()), GoodsSku.class);
            merchantIds.add(sku.getMerchant().getId());
        }

        List<WebUser> merchants = queryChannelService.findAll(QWebUser.webUser.id.in(merchantIds), WebUser.class);

        //保存所有的购物卡消费记录
        List<ShoppingCardRecordConsume> consumes = new ArrayList<>();

        for (WebUser merchant : merchants) {

            Order order = new Order();

            //商家向供应商的采购订单
            if ("SUPPLIER".equals(merchant.getRole().getName()) && "MERCHANT".equals(member.getRole().getName())) {
                order.setIsSupplier(1);
            }

            //一键上架商品订单
            if (orderDTO.getIsIssuingType() == 1) {

                GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(orderDTO.getDetails().get(0).getId()), GoodsSku.class);
                WebUser supplier = sku.getGoods().getIssuingGoods().getMerchant();

                order.setIsIssuingType(1);
                order.setSupplier(supplier);
            }

            order.setMember(member);
            order.setMerchant(merchant);
            order.setCreateTime(new Timestamp(System.currentTimeMillis()));
            order.setDeliveryName(orderDTO.getDeliveryName());
            order.setDeliveryProvince(orderDTO.getDeliveryProvince());
            order.setDeliveryCity(orderDTO.getDeliveryCity());
            order.setDeliveryArea(orderDTO.getDeliveryArea());
            order.setDeliveryAddress(orderDTO.getDeliveryAddress());
            order.setDeliveryMobile(orderDTO.getDeliveryMobile());
            order.setShippingMethod(orderDTO.getShippingMethod());

            String orderNo = DateUtil.format(new Date(), "yyyyMMddHHmmss") + merchant.getId() + member.getId();
            order.setOrderNo(orderNo);

            order.setStatus(1);
            order.setPayStatus(2);

            order.setInvoiceTFN(orderDTO.getInvoiceTFN());
            order.setInvoiceTitle(orderDTO.getInvoiceTitle());
            order.setHaveInvoice(orderDTO.getHaveInvoice());
            order.setInvoiceTitleType(orderDTO.getInvoiceTitleType());
            order.setInvoiceType(orderDTO.getInvoiceType());

            //优惠券剩余金额，如果订单使用了优惠券
            double couponPrice = 0;

            //优惠券过一轮，如果订单总价小于等于0，那么不满足优惠券的使用要求，第二轮过购物卡
            for (CouponDTO couponItem : orderDTO.getCoupons()) {
                if (couponItem.getMerchantId() == merchant.getId() && couponItem.getCouponId() > 0) {
                    order.setHaveCoupon(1);
                    Coupon coupon = queryChannelService.findOne(QCoupon.coupon.id.eq(couponItem.getCouponId()), Coupon.class);

                    CouponMemberDraw memberDraw = queryChannelService.findOne(QCouponMemberDraw.couponMemberDraw.coupon.id.eq(coupon.getId())
                            .and(QCouponMemberDraw.couponMemberDraw.member.id.eq(order.getMember().getId()).and(QCouponMemberDraw.couponMemberDraw.status.eq(1))), CouponMemberDraw.class);
                    Requires.notNull(memberDraw, "优惠券无法使用");
                    memberDraw.setStatus(2);
                    memberDrawRepository.save(memberDraw);

                    order.setCoupon(coupon);
                    couponPrice = coupon.getDenominationAmount();
                    break;
                }
            }


            ShoppingCardRecord merchantRecord = null;
            for (ShoppingCardRecordDTO item : orderDTO.getShoppingCardRecords()) {
                if (item.getMerchantId() == merchant.getId() && item.getShoppingCardRecordId() != 0) {
                    merchantRecord = queryChannelService.findOne(QShoppingCardRecord.shoppingCardRecord.id.in(item.getShoppingCardRecordId()), ShoppingCardRecord.class);
                    break;
                }
            }

            if (merchantRecord != null) {
                order.setHavaShoppingCardRecord(1);
                order.setShoppingCardRecord(merchantRecord);
            }

            for (GiftActivityDTO giftActivityDTO : orderDTO.getGiftActivities()) {
                if (giftActivityDTO.getMerchantId() == merchant.getId() && giftActivityDTO.getGiftActivityId() != 0) {
                    order.setMarketingType(1);
                    order.setGiftActivity(queryChannelService.findOne(QGiftActivity.giftActivity.id.eq(giftActivityDTO.getGiftActivityId()), GiftActivity.class));
                }
            }

            orderRepository.save(order);

            double freightPrice = 0;
            int quantity = 0;

            List<Goods> result = Lists.newArrayList();
            Map<Long, Integer> numbers = Maps.newHashMap();
            Map<Long, Double> grams = Maps.newHashMap();

            // 当前订单使用的购物卡金额
            double shoppingCardMoney = 0;

            //当前订单使用的优惠券金额`
            double couponMoney = 0;

            List<OrderDetail> details = new ArrayList<>();

            //商品小计价格
            double goodsSubtotalPrice = 0;

            //订单详情
            for (OrderDetailDTO skuParams : orderDTO.getDetails()) {

                GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(skuParams.getId()), GoodsSku.class);
                double price = 0;

                if (sku.getMerchant().getId() == merchant.getId()) {

                    //秒杀活动商品
                    if (sku.getGoods().getMarketingType() == 2 && sku.getGoods().getSeckillStatus() == 5 && sku.getGoods().getSeckillStore() != 0) {
                        if (skuParams.getQuantity() > sku.getSeckillStore()) {
                            throw new InterfaceException("库存不足");
                        }
                        if (skuParams.getQuantity() > sku.getSeckillLimit()) {
                            throw new InterfaceException("超过限购数量");
                        }
                        price = ArithUtils.mul(sku.getSeckillPrice(), skuParams.getQuantity());     //单价 * 数量
                        order.setMarketingType(4);
                    }

                    //特价活动商品
                    if (sku.getGoods().getMarketingType() == 1 && sku.getGoods().getBargainStatus() == 5) {
                        if (skuParams.getQuantity() > sku.getBargainStore()) {
                            throw new InterfaceException("库存不足");
                        }
                        price = ArithUtils.mul(sku.getBargainPrice(), skuParams.getQuantity());     //单价 * 数量
                        order.setMarketingType(3);
                    }

                    //普通商品
                    int marketingType = sku.getGoods().getMarketingType();

                    if (sku.getGoods().getMarketingType() == 0 && skuParams.getQuantity() > sku.getStore()) {
                        throw new InterfaceException("库存不足");
                    }

                    if (isGenrateGoodsPrice(sku, marketingType)) {
                        if (order.getIsSupplier() == 1) {
                            price = ArithUtils.mul(goodsApplication.getSupplierLeverPrice(sku, skuParams.getQuantity()), skuParams.getQuantity());     //单价 * 数量
                        } else {
                            price = ArithUtils.mul(sku.getPrice(), skuParams.getQuantity());     //单价 * 数量
                        }
                    }


                    if (price < 0) {
                        price = 0;
                    }

                    goodsSubtotalPrice += price;

                    OrderDetail detail = new OrderDetail();
                    details.add(detail);

                    //优惠券处理
                    if (price > 0 && couponPrice > 0 && havaUseCoupon(sku, order.getCoupon())) {
                        if (price - couponPrice > 0) {
                            couponMoney += couponPrice;
                            price -= couponPrice;
                            couponPrice = 0;
                        } else if (price - couponPrice < 0) {
                            couponMoney += price;
                            price = 0;
                            couponPrice -= price;
                        } else {
                            couponMoney += price;
                            price = 0;
                            couponPrice = 0;
                        }
                    }
                    detail.setSku(sku);
                    detail.setProductNo(sku.getGoods().getGoodsNo());
                    detail.setDefaultImage(sku.getGoods().getDefaultImage());
                    detail.setGoodsName(sku.getGoods().getName());
                    detail.setSpecs(sku.getAttribute1().getName() + " " + (null != sku.getAttribute2() ? sku.getAttribute2().getName() : ""));
                    detail.setQuantity(skuParams.getQuantity());
                    detail.setPrice(price);
                    detail.setOrder(order);
                    detail.setUnitPrice(sku.getPrice());

                    //秒杀活动商品
                    if (sku.getGoods().getMarketingType() == 2 && sku.getGoods().getSeckillStatus() == 5) {
                        detail.setMarketingType(4);
                        detail.setUnitPrice(sku.getSeckillPrice());
                        detail.setSeckillSession(sku.getGoods().getSeckillSession());
                    }

                    //特价活动商品
                    if (sku.getGoods().getMarketingType() == 1 && sku.getGoods().getBargainStatus() == 5) {
                        detail.setMarketingType(3);
                        detail.setUnitPrice(sku.getBargainPrice());
                    }

                    quantity = quantity + skuParams.getQuantity();

                    ShoppingCart cart = queryChannelService.findOne(QShoppingCart.shoppingCart.member.eq(order.getMember()).and(QShoppingCart.shoppingCart.sku.eq(sku)), ShoppingCart.class);
                    if (null != cart) {
                        cartRepository.delete(cart);
                    }

                    Goods goods = sku.getGoods();
                    if (numbers.containsKey(goods.getId())) {
                        int count = numbers.get(goods.getId());
                        double gram = grams.get(goods.getId());
                        numbers.put(goods.getId(), count + skuParams.getQuantity());
                        grams.put(goods.getId(), gram + goods.getGram());
                    } else {
                        numbers.put(goods.getId(), skuParams.getQuantity());
                        grams.put(goods.getId(), goods.getGram());
                        result.add(goods);
                    }
                }
                order.setNote(skuParams.getNote());
            }

            Requires.isTrue(couponPrice == 0, "订单不满足优惠券使用条件");

            // 购物卡处理
            if (merchantRecord != null) {
                for (OrderDetail detail : details) {
                    double price = detail.getPrice();
                    if (price <= 0) {
                        continue;
                    }
                    if (merchantRecord.getBalance() > 0 && havaUseRecord(merchantRecord, detail.getSku())) {

                        double currentPrice;

                        if (price > merchantRecord.getBalance()) {
                            currentPrice = merchantRecord.getBalance();
                            merchantRecord.setBalance(0);
                            merchantRecord.setStatus(2);
                            price = ArithUtils.sub(price, currentPrice);
                        } else if (price == merchantRecord.getBalance()) {
                            currentPrice = merchantRecord.getBalance();
                            merchantRecord.setBalance(0);
                            merchantRecord.setStatus(2);
                            price = 0;
                        } else {
                            currentPrice = price;
                            merchantRecord.setBalance(ArithUtils.sub(merchantRecord.getBalance(), price));
                            price = 0;
                        }
                        detail.setPrice(price);
//
//                      // 购物卡消费记录
                        ShoppingCardRecordConsume consume = new ShoppingCardRecordConsume();
                        consume.setCreateTime(new Timestamp(System.currentTimeMillis()));
                        consume.setBalance(merchantRecord.getBalance());
                        consume.setPrice(currentPrice);
                        consume.setOrder(order);
                        consume.setOrderDetail(detail);
                        consume.setShoppingCardRecord(merchantRecord);
                        consumes.add(consume);

                        shoppingCardRecordRepository.save(merchantRecord);
                        shoppingCardMoney = ArithUtils.add(currentPrice, shoppingCardMoney);
                    }
                }
            }
            detailRepository.save(details);

            for (Goods goods : result) {
                int count = numbers.get(goods.getId());
                double gramCount = grams.get(goods.getId());

                //运费计算逻辑
                if (count != 0) {
                    if (goods.getPostageType() == 1) {     //走运费模板

                        MerchantFreight freight = queryChannelService.findOne(QMerchantFreight.merchantFreight.city.eq(order.getDeliveryCity()).and(QMerchantFreight.merchantFreight.merchant.eq(merchant).and(QMerchantFreight.merchantFreight.template.id.eq(goods.getFreightTemplate().getId()))), MerchantFreight.class);

                        MerchantFreightTemplate template = queryChannelService.findOne(QMerchantFreightTemplate.merchantFreightTemplate.id.eq(goods.getFreightTemplate().getId()), MerchantFreightTemplate.class);

                        //按重量
                        if (template.getType() == 1) {

                            double gram = ArithUtils.mul(gramCount, count);

                            if (null != freight) {   //拿到了模板内设置的区域运费

                                if (gram <= freight.getFirstWeight()) {
                                    freightPrice += freight.getFirstWeightAmount();
                                } else {
                                    double fistWeightAmount = freight.getFirstWeightAmount();
                                    double weight = ArithUtils.sub(gram, freight.getFirstWeight());

                                    if (weight < freight.getOtherWeight()) {
                                        freightPrice += ArithUtils.add(fistWeightAmount, freight.getOtherWeightAmount());
                                    } else {
                                        freightPrice += ArithUtils.add(fistWeightAmount, ArithUtils.mul(Math.ceil(ArithUtils.div(weight, freight.getOtherWeight(), 2)), freight.getOtherWeightAmount()));
                                    }
                                }

                            } else {

                                if (gram <= template.getDefaultWeight()) {
                                    freightPrice += template.getDefaultWeightAmount();
                                } else {

                                    double fistWeightAmount = template.getDefaultWeightAmount();
                                    double weight = ArithUtils.sub(gram, template.getDefaultWeight());

                                    if (weight < template.getDefaultAddWeight()) {
                                        freightPrice += ArithUtils.add(fistWeightAmount, template.getDefaultAddWeightAmount());
                                    } else {
                                        freightPrice += ArithUtils.add(fistWeightAmount, ArithUtils.mul(Math.ceil(ArithUtils.div(weight, template.getDefaultAddWeight(), 2)), template.getDefaultAddWeightAmount()));
                                    }
                                }

                            }

                        }


                        //按件
                        if (template.getType() == 2) {

                            if (null != freight) {

                                if (count <= freight.getFirstPiece()) {
                                    freightPrice += freight.getFirstPieceAmount();
                                } else {
                                    freightPrice += ArithUtils.add(freight.getFirstPieceAmount(), ArithUtils.mul(ArithUtils.sub(count, freight.getFirstPiece()), freight.getOtherPieceAmount()));
                                }

                            } else {

                                if (count <= template.getDefaultPiece()) {
                                    freightPrice += template.getDefaultPieceAmount();
                                } else {
                                    freightPrice += ArithUtils.add(template.getDefaultPieceAmount(), ArithUtils.mul(ArithUtils.sub(count, template.getDefaultPiece()), template.getDefaultAddPieceAmount()));
                                }

                            }

                        }


                    } else if (goods.getPostageType() == 2) {      //包邮
                        freightPrice += ArithUtils.add(freightPrice, 0);

                    } else if (goods.getPostageType() == 3) {       //指定运费

                        freightPrice += ArithUtils.add(freightPrice, ArithUtils.mul(goods.getPostage(), count));
                    }

                }


            }

            if (order.getShippingMethod() == 2) {
                freightPrice = 0;
                order.setShippingAddress(order.getMerchant().getWarehouseAddress());
            }

            order.setGoodsSubtotalPrice(ArithUtils.roundHalfUp(goodsSubtotalPrice, 2));
            order.setFreightPrice(ArithUtils.roundHalfUp(freightPrice, 2));
            order.setShoppingCardMoney(ArithUtils.roundHalfUp(shoppingCardMoney, 2));
            order.setPrice(ArithUtils.roundHalfUp(goodsSubtotalPrice + freightPrice - couponMoney, 2));
            order.setMoney(ArithUtils.roundHalfUp(order.getPrice() - shoppingCardMoney, 2));

            order.setGoodsQuantity(quantity);
            order.setAutoCancelTime(DateUtil.offsetHour(new Date(), 1).toTimestamp());
            orderRepository.save(order);

            //使用了赠品券，扣除赠品库存
            if (order.getHaveCoupon() == 1 && order.getCoupon() != null && order.getCoupon().getType() == 2) {
                Goods goods = order.getCoupon().getComplimentaryGoods();
                if (goods != null) {
                    goods.setSalesVolume(goods.getSalesVolume() + 1);
                    goods.setStore(goods.getStore() - 1);
                }
            }

            List<OrderDetail> orderDetails = queryChannelService.findAll(QOrderDetail.orderDetail.order.id.eq(order.getId()), OrderDetail.class);

            //减库存，加销量
            for (OrderDetail detail : orderDetails) {
                GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.eq(detail.getSku()), GoodsSku.class);
                Goods goods = queryChannelService.findOne(QGoods.goods.eq(sku.getGoods()), Goods.class);

                synchronized (SyncLock.getLock(String.valueOf(goods.getId()))) {

                    sku.setStore(Math.max((sku.getStore() - detail.getQuantity()), 0));

                    //秒杀活动商品
                    if (sku.getGoods().getMarketingType() == 2 && sku.getGoods().getSeckillStatus() == 5) {
                        sku.setSeckillStore(Math.max((sku.getSeckillStore() - detail.getQuantity()), 0));

                        goods.setSeckillSalesVolume(goods.getSeckillSalesVolume() + detail.getQuantity());
                        goods.setSeckillStore(Math.max((goods.getSeckillStore() - detail.getQuantity()), 0));

                        if (goods.getSeckillStore() == 0) {
                            goods.setSeckillStatus(6);
                        }

                    }

                    //特价活动商品
                    if (sku.getGoods().getMarketingType() == 1 && sku.getGoods().getBargainStatus() == 5) {
                        sku.setBargainStore(Math.max((sku.getBargainStore() - detail.getQuantity()), 0));
                        goods.setBargainSalesVolume(goods.getBargainSalesVolume() + detail.getQuantity());
                        goods.setBargainStore(Math.max((goods.getBargainStore() - detail.getQuantity()), 0));
                        if (goods.getBargainStore() == 0) {
                            goods.setBargainStatus(6);
                        }
                    }
                    skuRepository.save(sku);

                    goods.setStore(Math.max((goods.getStore() - detail.getQuantity()), 0));
                    goods.setSalesVolume(goods.getSalesVolume() + detail.getQuantity());

                    if (goods.getStore() == 0) {
                        goods.setStatus(6);
                    }

                    goodsRepository.save(goods);
                }
            }
            orders.add(order);
        }

        shoppingCardRecordConsumeRepository.save(consumes);

        return orders;
    }

    /**
     * 判断当前sku是否可以使用优惠券
     *
     * @param sku    sku
     * @param coupon 优惠券
     */
    private boolean havaUseCoupon(GoodsSku sku, Coupon coupon) {
        if (coupon.getType() == 2) {
            return false;
        }
        if (coupon.getScopeType() == 1) {
            return sku.getGoods().getMerchant().getId() == coupon.getMerchant().getId();
        }
        int count = queryChannelService.selectCount("select count(*) from mall_coupon_goods where goods_id = :gid and coupon_id = :cid", ImmutableMap.of("gid", sku.getGoods().getId(), "cid", coupon.getId()));
        return count > 0;
    }

    private boolean isGenrateGoodsPrice(GoodsSku sku, int marketingType) {
        return (marketingType == 4 && sku.getGoods().getGroupBookingStatus() == 5) || (marketingType == 2 && sku.getGoods().getSeckillStore() == 0) || (marketingType == 1 && sku.getGoods().getBargainStatus() == 0) || marketingType == 0 || (marketingType == 1 && sku.getGoods().getBargainStatus() != 5) || (marketingType == 1 && sku.getGoods().getBargainStatus() == 5 && sku.getGoods().getBargainStore() == 0) || (marketingType == 2 && sku.getGoods().getSeckillStatus() != 5) || (marketingType == 3 && sku.getGoods().getPresellStatus() != 5) || (marketingType == 4 && sku.getGoods().getGroupBookingStatus() != 5);
    }


    /**
     * 提交分销订单
     */
    public List<Order> submitDistribution(WebUser member, OrderDTO orderDTO) {

        Requires.isTrue(orderDTO.getOrderType() == 1 || orderDTO.getOrderType() == 2, "订单类型不正确");
        List<Order> orders = new ArrayList<>();
        Set<Long> merchantIds = new HashSet<>();

        for (OrderDetailDTO skuParams : orderDTO.getDetails()) {
            GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(skuParams.getId()), GoodsSku.class);
            merchantIds.add(sku.getMerchant().getId());
        }

        List<WebUser> merchants = queryChannelService.findAll(QWebUser.webUser.id.in(merchantIds), WebUser.class);

        for (WebUser merchant : merchants) {
            Order order = new Order();
            if (orderDTO.getOrderType() == 1) {
                order.setApplyDistributor(orderDTO.getLevel());
            } else {
                order.setDistributionOrder(1);
                order.setDistributor(queryChannelService.findOne(QDistributor.distributor.id.eq(orderDTO.getDistributorId()), Distributor.class));
                order.setDistributorSource(orderDTO.getDistributorSource());
            }
            order.setMember(member);
            order.setMerchant(merchant);
            order.setCreateTime(new Timestamp(System.currentTimeMillis()));
            order.setDeliveryName(orderDTO.getDeliveryName());
            order.setDeliveryProvince(orderDTO.getDeliveryProvince());
            order.setDeliveryCity(orderDTO.getDeliveryCity());
            order.setDeliveryArea(orderDTO.getDeliveryArea());
            order.setDeliveryAddress(orderDTO.getDeliveryAddress());
            order.setDeliveryMobile(orderDTO.getDeliveryMobile());
            order.setShippingMethod(orderDTO.getShippingMethod());

            String orderNo = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + merchant.getId() + member.getId() + RandomStringUtils.randomNumeric(6);
            order.setOrderNo(orderNo);

            order.setStatus(1);
            order.setPayStatus(2);

            order.setInvoiceTFN(orderDTO.getInvoiceTFN());
            order.setInvoiceTitle(orderDTO.getInvoiceTitle());
            order.setHaveInvoice(orderDTO.getHaveInvoice());
            order.setInvoiceTitleType(orderDTO.getInvoiceTitleType());
            order.setInvoiceType(orderDTO.getInvoiceType());
            orderRepository.save(order);

            double freightPrice = 0;
            double goodsSubtotalPrice = 0;
            int quantity = 0;

            List<Goods> result = new ArrayList<>();
            Map<Long, Integer> numbers = new HashMap<>();
            Map<Long, Double> grams = new HashMap<>();

            //订单详情
            for (OrderDetailDTO skuParams : orderDTO.getDetails()) {

                GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(skuParams.getId()), GoodsSku.class);

                if (sku.getMerchant().getId() == merchant.getId()) {
                    if (skuParams.getQuantity() > sku.getStore()) {
                        throw new InterfaceException("库存不足");
                    }

                    double price = ArithUtils.mul(sku.getPrice(), skuParams.getQuantity());

                    if (price < 0) {
                        price = 0;
                    }

                    OrderDetail detail = new OrderDetail();

                    detail.setSku(sku);
                    detail.setProductNo(sku.getGoods().getGoodsNo());
                    detail.setDefaultImage(sku.getGoods().getDefaultImage());
                    detail.setGoodsName(sku.getGoods().getName());
                    detail.setSpecs(sku.getAttribute1().getName() + " " + (null != sku.getAttribute2() ? sku.getAttribute2().getName() : ""));
                    detail.setQuantity(skuParams.getQuantity());
                    detail.setPrice(price);
                    detail.setOrder(order);
                    detail.setUnitPrice(sku.getPrice());

                    detailRepository.save(detail);


                    goodsSubtotalPrice = ArithUtils.add(goodsSubtotalPrice, price);
                    quantity += skuParams.getQuantity();

                    ShoppingCart cart = queryChannelService.findOne(QShoppingCart.shoppingCart.member.eq(order.getMember()).and(QShoppingCart.shoppingCart.sku.eq(sku)), ShoppingCart.class);
                    if (null != cart) {
                        cartRepository.delete(cart);
                    }

                    Goods goods = sku.getGoods();

                    if (numbers.containsKey(goods.getId())) {
                        int count = numbers.get(goods.getId());
                        double gram = grams.get(goods.getId());
                        numbers.put(goods.getId(), count + skuParams.getQuantity());
                        grams.put(goods.getId(), gram + goods.getGram());
                    } else {
                        numbers.put(goods.getId(), skuParams.getQuantity());
                        grams.put(goods.getId(), goods.getGram());
                        result.add(goods);
                    }
                }
                order.setNote(skuParams.getNote());
            }

            if (order.getShippingMethod() == 1) {
                for (Goods goods : result) {
                    int count = numbers.get(goods.getId());
                    double gramCount = grams.get(goods.getId());
                    //运费计算逻辑
                    if (count != 0) {
                        if (goods.getPostageType() == 1) {     //走运费模板

                            MerchantFreight freight = queryChannelService.findOne(QMerchantFreight.merchantFreight.city.eq(order.getDeliveryCity()).and(QMerchantFreight.merchantFreight.merchant.eq(merchant).and(QMerchantFreight.merchantFreight.template.id.eq(goods.getFreightTemplate().getId()))), MerchantFreight.class);
                            MerchantFreightTemplate template = queryChannelService.findOne(QMerchantFreightTemplate.merchantFreightTemplate.id.eq(goods.getFreightTemplate().getId()), MerchantFreightTemplate.class);

                            //按重量
                            if (template.getType() == 1) {

                                double gram = ArithUtils.mul(gramCount, count);//总重量

                                if (null != freight) {   //拿到了模板内设置的区域运费
                                    if (gram <= freight.getFirstWeight()) {
                                        freightPrice += freight.getFirstWeightAmount();
                                    } else {
                                        double fistWeightAmount = freight.getFirstWeightAmount();
                                        double weight = ArithUtils.sub(gram, freight.getFirstWeight());

                                        if (weight < freight.getOtherWeight()) {
                                            freightPrice += ArithUtils.add(fistWeightAmount, freight.getOtherWeightAmount());
                                        } else {
                                            freightPrice += ArithUtils.add(fistWeightAmount, ArithUtils.mul(Math.ceil(ArithUtils.div(weight, freight.getOtherWeight(), 2)), freight.getOtherWeightAmount()));
                                        }
                                    }

                                } else {

                                    if (gram <= template.getDefaultWeight()) {
                                        freightPrice += template.getDefaultWeightAmount();
                                    } else {

                                        double fistWeightAmount = template.getDefaultWeightAmount();
                                        double weight = ArithUtils.sub(gram, template.getDefaultWeight());

                                        if (weight < template.getDefaultAddWeight()) {
                                            freightPrice += ArithUtils.add(fistWeightAmount, template.getDefaultAddWeightAmount());
                                        } else {
                                            freightPrice += ArithUtils.add(fistWeightAmount, ArithUtils.mul(Math.ceil(ArithUtils.div(weight, template.getDefaultAddWeight(), 2)), template.getDefaultAddWeightAmount()));
                                        }
                                    }

                                }

                            }


                            //按件
                            if (template.getType() == 2) {

                                if (null != freight) {

                                    if (count <= freight.getFirstPiece()) {
                                        freightPrice += freight.getFirstPieceAmount();
                                    } else {
                                        freightPrice += ArithUtils.add(freight.getFirstPieceAmount(), ArithUtils.mul(ArithUtils.sub(count, freight.getFirstPiece()), freight.getOtherPieceAmount()));
                                    }

                                } else {

                                    if (count <= template.getDefaultPiece()) {
                                        freightPrice += template.getDefaultPieceAmount();
                                    } else {
                                        freightPrice += ArithUtils.add(template.getDefaultPieceAmount(), ArithUtils.mul(ArithUtils.sub(count, template.getDefaultPiece()), template.getDefaultAddPieceAmount()));
                                    }

                                }

                            }


                        } else if (goods.getPostageType() == 2) {      //包邮
                            freightPrice += ArithUtils.add(freightPrice, 0);
                        } else if (goods.getPostageType() == 3) {       //指定运费
                            freightPrice += ArithUtils.add(freightPrice, ArithUtils.mul(goods.getPostage(), count));
                        }

                    }
                }
            }

            if (order.getShippingMethod() == 2) {
                freightPrice = 0;
                order.setShippingAddress(order.getMerchant().getWarehouseAddress());
            }

            double totalPrice = ArithUtils.add(freightPrice, goodsSubtotalPrice);

            order.setFreightPrice(freightPrice);
            order.setGoodsSubtotalPrice(goodsSubtotalPrice);
            order.setPrice(totalPrice);
            order.setMoney(totalPrice);
            order.setGoodsQuantity(quantity);
            order.setAutoCancelTime(new Timestamp(System.currentTimeMillis() + 3600 * 1000));
            orderRepository.save(order);

            List<OrderDetail> orderDetails = queryChannelService.findAll(QOrderDetail.orderDetail.order.id.eq(order.getId()), OrderDetail.class);

            //减库存，加销量
            for (OrderDetail detail : orderDetails) {
                GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.eq(detail.getSku()), GoodsSku.class);
                Goods goods = queryChannelService.findOne(QGoods.goods.eq(sku.getGoods()), Goods.class);

                sku.setStore(Math.max((sku.getStore() - detail.getQuantity()), 0));
                skuRepository.save(sku);

                goods.setStore(Math.max((goods.getStore() - detail.getQuantity()), 0));
                goods.setSalesVolume(goods.getSalesVolume() + detail.getQuantity());

                if (goods.getStore() <= 0) {
                    goods.setStatus(6);
                }
                goodsRepository.save(goods);
            }
            orders.add(order);
        }
        return orders;
    }

    public List<Order> submitLiveOrder(WebUser member, OrderDTO orderDTO) {

        List<Order> orders = new ArrayList<>();
        Set<Long> merchantIds = new HashSet<>();

        for (OrderDetailDTO skuParams : orderDTO.getDetails()) {
            GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(skuParams.getId()), GoodsSku.class);
            merchantIds.add(sku.getMerchant().getId());
        }

        List<WebUser> merchants = queryChannelService.findAll(QWebUser.webUser.id.in(merchantIds), WebUser.class);

        for (WebUser merchant : merchants) {
            Order order = new Order();
            order.setLiveSession(queryChannelService.findOne(LiveSession.class, orderDTO.getLiveSessionId()));
            Requires.notNull(order.getLiveSession(), "直播间不存在");
            order.setMember(member);
            order.setMerchant(merchant);
            order.setCreateTime(new Timestamp(System.currentTimeMillis()));
            order.setDeliveryName(orderDTO.getDeliveryName());
            order.setDeliveryProvince(orderDTO.getDeliveryProvince());
            order.setDeliveryCity(orderDTO.getDeliveryCity());
            order.setDeliveryArea(orderDTO.getDeliveryArea());
            order.setDeliveryAddress(orderDTO.getDeliveryAddress());
            order.setDeliveryMobile(orderDTO.getDeliveryMobile());
            order.setShippingMethod(orderDTO.getShippingMethod());

            String orderNo = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + merchant.getId() + member.getId();
            order.setOrderNo(orderNo);
            order.setStatus(1);
            order.setPayStatus(2);
            orderRepository.save(order);

            double freightPrice = 0;
            double goodsSubtotalPrice = 0;
            int quantity = 0;

            List<Goods> result = new ArrayList<>();
            Map<Long, Integer> numbers = new HashMap<>();
            Map<Long, Double> grams = new HashMap<>();

            //订单详情
            for (OrderDetailDTO skuParams : orderDTO.getDetails()) {

                GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(skuParams.getId()), GoodsSku.class);

                if (sku.getMerchant().getId() == merchant.getId()) {
                    if (skuParams.getQuantity() > sku.getStore()) {
                        throw new InterfaceException("库存不足");
                    }

                    double price = ArithUtils.mul(sku.getPrice(), skuParams.getQuantity());

                    if (price < 0) {
                        price = 0;
                    }

                    OrderDetail detail = new OrderDetail();

                    detail.setSku(sku);
                    detail.setProductNo(sku.getGoods().getGoodsNo());
                    detail.setDefaultImage(sku.getGoods().getDefaultImage());
                    detail.setGoodsName(sku.getGoods().getName());
                    detail.setSpecs(sku.getAttribute1().getName() + " " + (null != sku.getAttribute2() ? sku.getAttribute2().getName() : ""));
                    detail.setQuantity(skuParams.getQuantity());
                    detail.setPrice(price);
                    detail.setOrder(order);
                    detail.setUnitPrice(sku.getPrice());

                    detailRepository.save(detail);


                    goodsSubtotalPrice = ArithUtils.add(goodsSubtotalPrice, price);
                    quantity += skuParams.getQuantity();

                    ShoppingCart cart = queryChannelService.findOne(QShoppingCart.shoppingCart.member.eq(order.getMember()).and(QShoppingCart.shoppingCart.sku.eq(sku)), ShoppingCart.class);
                    if (null != cart) {
                        cartRepository.delete(cart);
                    }

                    Goods goods = sku.getGoods();

                    if (numbers.containsKey(goods.getId())) {
                        int count = numbers.get(goods.getId());
                        double gram = grams.get(goods.getId());
                        numbers.put(goods.getId(), count + skuParams.getQuantity());
                        grams.put(goods.getId(), gram + goods.getGram());
                    } else {
                        numbers.put(goods.getId(), skuParams.getQuantity());
                        grams.put(goods.getId(), goods.getGram());
                        result.add(goods);
                    }
                }
                order.setNote(skuParams.getNote());
            }

            if (order.getShippingMethod() == 1) {
                for (Goods goods : result) {
                    int count = numbers.get(goods.getId());
                    double gramCount = grams.get(goods.getId());
                    //运费计算逻辑
                    if (count != 0) {
                        if (goods.getPostageType() == 1) {     //走运费模板

                            MerchantFreight freight = queryChannelService.findOne(QMerchantFreight.merchantFreight.city.eq(order.getDeliveryCity()).and(QMerchantFreight.merchantFreight.merchant.eq(merchant).and(QMerchantFreight.merchantFreight.template.id.eq(goods.getFreightTemplate().getId()))), MerchantFreight.class);
                            MerchantFreightTemplate template = queryChannelService.findOne(QMerchantFreightTemplate.merchantFreightTemplate.id.eq(goods.getFreightTemplate().getId()), MerchantFreightTemplate.class);

                            //按重量
                            if (template.getType() == 1) {

                                double gram = ArithUtils.mul(gramCount, count);//总重量

                                if (null != freight) {   //拿到了模板内设置的区域运费
                                    if (gram <= freight.getFirstWeight()) {
                                        freightPrice += freight.getFirstWeightAmount();
                                    } else {
                                        double fistWeightAmount = freight.getFirstWeightAmount();
                                        double weight = ArithUtils.sub(gram, freight.getFirstWeight());

                                        if (weight < freight.getOtherWeight()) {
                                            freightPrice += ArithUtils.add(fistWeightAmount, freight.getOtherWeightAmount());
                                        } else {
                                            freightPrice += ArithUtils.add(fistWeightAmount, ArithUtils.mul(Math.ceil(ArithUtils.div(weight, freight.getOtherWeight(), 2)), freight.getOtherWeightAmount()));
                                        }
                                    }

                                } else {

                                    if (gram <= template.getDefaultWeight()) {
                                        freightPrice += template.getDefaultWeightAmount();
                                    } else {

                                        double fistWeightAmount = template.getDefaultWeightAmount();
                                        double weight = ArithUtils.sub(gram, template.getDefaultWeight());

                                        if (weight < template.getDefaultAddWeight()) {
                                            freightPrice += ArithUtils.add(fistWeightAmount, template.getDefaultAddWeightAmount());
                                        } else {
                                            freightPrice += ArithUtils.add(fistWeightAmount, ArithUtils.mul(Math.ceil(ArithUtils.div(weight, template.getDefaultAddWeight(), 2)), template.getDefaultAddWeightAmount()));
                                        }
                                    }

                                }

                            }


                            //按件
                            if (template.getType() == 2) {

                                if (null != freight) {

                                    if (count <= freight.getFirstPiece()) {
                                        freightPrice += freight.getFirstPieceAmount();
                                    } else {
                                        freightPrice += ArithUtils.add(freight.getFirstPieceAmount(), ArithUtils.mul(ArithUtils.sub(count, freight.getFirstPiece()), freight.getOtherPieceAmount()));
                                    }

                                } else {

                                    if (count <= template.getDefaultPiece()) {
                                        freightPrice += template.getDefaultPieceAmount();
                                    } else {
                                        freightPrice += ArithUtils.add(template.getDefaultPieceAmount(), ArithUtils.mul(ArithUtils.sub(count, template.getDefaultPiece()), template.getDefaultAddPieceAmount()));
                                    }

                                }

                            }


                        } else if (goods.getPostageType() == 2) {      //包邮
                            freightPrice += ArithUtils.add(freightPrice, 0);
                        } else if (goods.getPostageType() == 3) {       //指定运费
                            freightPrice += ArithUtils.add(freightPrice, ArithUtils.mul(goods.getPostage(), count));
                        }

                    }
                }
            }

            if (order.getShippingMethod() == 2) {
                freightPrice = 0;
                order.setShippingAddress(order.getMerchant().getWarehouseAddress());
            }

            double totalPrice = ArithUtils.add(freightPrice, goodsSubtotalPrice);

            order.setFreightPrice(freightPrice);
            order.setGoodsSubtotalPrice(goodsSubtotalPrice);
            order.setPrice(totalPrice);
            order.setMoney(totalPrice);
            order.setGoodsQuantity(quantity);
            order.setAutoCancelTime(new Timestamp(System.currentTimeMillis() + 3600 * 1000));
            orderRepository.save(order);

            List<OrderDetail> orderDetails = queryChannelService.findAll(QOrderDetail.orderDetail.order.id.eq(order.getId()), OrderDetail.class);

            //减库存，加销量
            for (OrderDetail detail : orderDetails) {
                GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.eq(detail.getSku()), GoodsSku.class);
                Goods goods = queryChannelService.findOne(QGoods.goods.eq(sku.getGoods()), Goods.class);

                sku.setStore(Math.max((sku.getStore() - detail.getQuantity()), 0));
                skuRepository.save(sku);

                goods.setStore(Math.max((goods.getStore() - detail.getQuantity()), 0));
                goods.setSalesVolume(goods.getSalesVolume() + detail.getQuantity());

                if (goods.getStore() <= 0) {
                    goods.setStatus(6);
                }
                goodsRepository.save(goods);
            }
            orders.add(order);
        }
        return orders;
    }


    /**
     * 取消订单
     */
    public void cancel(Order order, String note) throws Exception {
        if (order.getStatus() == 1) {
            order.setStatus(6);
            order.setCancelTime(new Timestamp(System.currentTimeMillis()));
            order.setCancelNote(note);
            orderRepository.save(order);

            List<OrderDetail> details = queryChannelService.findAll(QOrderDetail.orderDetail.order.id.eq(order.getId()), OrderDetail.class);

            for (OrderDetail detail : details) {
                GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.eq(detail.getSku()), GoodsSku.class);

                sku.setStore((sku.getStore() + detail.getQuantity()));

                //拼团活动订单
                if (detail.getMarketingType() == 2) {
                    sku.setGroupBookingStore(sku.getGroupBookingStore() + detail.getQuantity());
                }

                //特价活动商品
                if (detail.getMarketingType() == 3) {
                    sku.setBargainStore(sku.getBargainStore() + detail.getQuantity());
                }

                //秒杀活动商品
                if (detail.getMarketingType() == 4) {
                    sku.setSeckillStore(sku.getSeckillStore() + detail.getQuantity());
                }

                skuRepository.save(sku);

                Goods goods = queryChannelService.findOne(QGoods.goods.eq(sku.getGoods()), Goods.class);
                goods.setStore((goods.getStore() + detail.getQuantity()));
                goods.setSalesVolume(Math.max(goods.getSalesVolume() - detail.getQuantity(), 0));

                //拼团活动订单
                if (detail.getMarketingType() == 2) {
                    goods.setGroupBookingStore(goods.getGroupBookingStore() + detail.getQuantity());
                    goods.setGroupBookingSalesVolume(goods.getGroupBookingSalesVolume() - detail.getQuantity());

                    if (goods.getGroupBookingStatus() == 6 && new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(goods.getGroupBookingEndTime()).getTime() >= new Date().getTime()) {
                        goods.setGroupBookingStatus(5);
                    }
                }

                //特价活动商品
                if (detail.getMarketingType() == 3) {
                    goods.setBargainStore(goods.getBargainStatus() + detail.getQuantity());
                    goods.setBargainSalesVolume(goods.getBargainSalesVolume() - detail.getQuantity());
                    if (goods.getBargainStatus() == 6 && new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(goods.getEndDateOfValidity()).getTime() >= new Date().getTime()) {
                        goods.setBargainStatus(5);
                    }
                }

                //秒杀活动商品
                if (detail.getMarketingType() == 4) {
                    goods.setSeckillStore(goods.getSeckillStore() + detail.getQuantity());
                    goods.setSeckillSalesVolume(goods.getSeckillSalesVolume() - detail.getQuantity());
                    if (goods.getSeckillStatus() == 6 && new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(goods.getSeckillSession().getSeckillTime() + " " + goods.getSeckillSession().getSeckillEndTime()).getTime() >= new Date().getTime()) {
                        goods.setSeckillStatus(5);
                    }
                }

                //预售活动商品
                if (detail.getMarketingType() == 5) {
                    goods.setPresellSalesVolume(goods.getPresellSalesVolume() - detail.getQuantity());
                }

                if (goods.getStatus() == 6) {
                    goods.setStatus(3);
                }
                goodsRepository.save(goods);
            }

            if (order.getHavaShoppingCardRecord() == 1) {
                recoverShoppingCard(order);
            }
        }
    }

    /**
     * 商品评价
     */
    public void comment(WebUser member, GoodsComment params, OrderDetail orderDetail) {

        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(params.getGoods().getId()), Goods.class);

        GoodsComment comment = new GoodsComment();
        comment.setStatus(2);
        comment.setGoods(goods);
        comment.setContent(params.getContent());
        comment.setMember(member);
        comment.setMerchant(goods.getMerchant());
        comment.setStarLever(params.getStarLever());
        comment.setCreateTime(new Timestamp(System.currentTimeMillis()));
        comment.setPlatformType(params.getPlatformType());

        commentRepository.save(comment);

        for (GoodsCommentImage item : params.getImages()) {

            GoodsCommentImage image = new GoodsCommentImage();
            image.setGoods(goods);
            image.setMerchant(goods.getMerchant());
            image.setComment(comment);
            image.setName(item.getName());
            image.setCreateTime(new Timestamp(System.currentTimeMillis()));
            commentImageRepository.save(image);

        }

        orderDetail.setCommentStatus(1);
        detailRepository.save(orderDetail);

        orderFinish(orderDetail.getOrder());

        if (!comment.getContent().equals("系统默认好评")) {
            AliYunSmsService.send(orderDetail.getOrder().getMerchant().getMobile(),
                    PropertiesHelps.getValue("sign_name"),
                    "SMS_211020803",
                    ImmutableMap.of("orderNo", orderDetail.getOrder().getOrderNo(), "evaluationResult", comment.getContent()));
        }


    }

    /**
     * 订单完成
     */
    private void orderFinish(Order order) {

        boolean isAllDetailComment = true;
        for (OrderDetail item : order.getDetails()) {
            if (item.getCommentStatus() == 0) {
                isAllDetailComment = false;
                break;
            }
        }

        //订单完成
        if (isAllDetailComment) {
            order.setStatus(5);
            orderRepository.save(order);

            if (order.getIsIssuingType() == 1) { //一键代发订单

                double issuingPrice = order.getDetails().get(0).getSku().getIssuingPrice();
                double price = order.getDetails().get(0).getSku().getPrice();

                double subtotalPriceOfMerchant = Math.max(ArithUtils.sub(price, issuingPrice), 0); //这是要给商家的商品金额

                //商家订单金额到账
                WebUser merchant = queryChannelService.findOne(QWebUser.webUser.eq(order.getMerchant()), WebUser.class);
                merchant.setBalance(ArithUtils.add(merchant.getBalance(), subtotalPriceOfMerchant));
                merchant.setTotalOrderAmount(ArithUtils.add(merchant.getTotalOrderAmount(), subtotalPriceOfMerchant));
                merchant.setTotalOrderNumber(merchant.getTotalOrderNumber() + 1);
                userRepository.save(merchant);

                //商户订单金额到账流水记录
                TradingLog tradingLog = new TradingLog();
                tradingLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
                tradingLog.setMerchant(merchant);
                tradingLog.setStatus(1);
                tradingLog.setType(1);
                tradingLog.setAmount(subtotalPriceOfMerchant);
                tradingLog.setOrderNo(order.getOrderNo());
                tradingLogRepository.save(tradingLog);

                //供应商订单金额到账
                WebUser supplier = queryChannelService.findOne(QWebUser.webUser.eq(order.getSupplier()), WebUser.class);
                supplier.setBalance(ArithUtils.add(supplier.getBalance(), issuingPrice));
                supplier.setTotalOrderAmount(ArithUtils.add(supplier.getTotalOrderAmount(), issuingPrice));
                supplier.setTotalOrderNumber(supplier.getTotalOrderNumber() + 1);
                userRepository.save(supplier);

                //供应商订单金额到账流水记录
                TradingLog tradingLogOfSupplier = new TradingLog();
                tradingLogOfSupplier.setCreateTime(new Timestamp(System.currentTimeMillis()));
                tradingLogOfSupplier.setMerchant(supplier);
                tradingLogOfSupplier.setStatus(1);
                tradingLogOfSupplier.setType(1);
                tradingLogOfSupplier.setAmount(issuingPrice);
                tradingLogOfSupplier.setOrderNo(order.getOrderNo());
                tradingLogRepository.save(tradingLogOfSupplier);

            } else {//正常订单

                WebUser merchant = queryChannelService.findOne(QWebUser.webUser.eq(order.getMerchant()), WebUser.class);

                if (order.getIsSupplier() == 1) {//商家采购订单

                    if (order.getPayMethod() != 5) {//非线下转账的订单
                        //商家订单金额到账
                        merchant.setBalance(ArithUtils.add(merchant.getBalance(), order.getPrice()));
                        merchant.setTotalOrderAmount(ArithUtils.add(merchant.getTotalOrderAmount(), order.getPrice()));
                        merchant.setTotalOrderNumber(merchant.getTotalOrderNumber() + 1);
                        userRepository.save(merchant);

                        //商户订单金额到账流水记录
                        TradingLog tradingLog = new TradingLog();
                        tradingLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
                        tradingLog.setMerchant(merchant);
                        tradingLog.setStatus(1);
                        tradingLog.setType(1);
                        tradingLog.setAmount(order.getPrice());
                        tradingLog.setOrderNo(order.getOrderNo());
                        tradingLogRepository.save(tradingLog);
                    } else {

                        //商家订单金额到账
                        merchant.setTotalOrderAmount(ArithUtils.add(merchant.getTotalOrderAmount(), order.getPrice()));
                        merchant.setTotalOrderNumber(merchant.getTotalOrderNumber() + 1);
                        userRepository.save(merchant);
                    }


                } else { //商城会员普通订单

                    if (order.getPayMethod() == 4) {

                        //商户订单金额到账流水记录
                        TradingLog tradingLog = new TradingLog();
                        tradingLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
                        tradingLog.setMerchant(merchant);
                        tradingLog.setStatus(1);
                        tradingLog.setType(1);

                        if (order.getDistributionPrice() != null && order.getDistributionPrice() > 0) {
                            tradingLog.setAmount(ArithUtils.sub(ArithUtils.add(order.getPrice(), order.getShoppingCardMoney()), order.getDistributionPrice()));
                        } else {
                            tradingLog.setAmount(ArithUtils.add(order.getPrice(), order.getShoppingCardMoney()));
                        }

                        tradingLog.setOrderNo(order.getOrderNo());
                        tradingLogRepository.save(tradingLog);

                        //商家订单金额到账
                        merchant.setBalance(ArithUtils.add(merchant.getBalance(), tradingLog.getAmount()));
                        merchant.setTotalOrderAmount(ArithUtils.add(merchant.getTotalOrderAmount(), tradingLog.getAmount()));
                        merchant.setTotalOrderNumber(merchant.getTotalOrderNumber() + 1);
                        userRepository.save(merchant);

                    } else {

                        //商户订单金额到账流水记录
                        TradingLog tradingLog = new TradingLog();
                        tradingLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
                        tradingLog.setMerchant(merchant);
                        tradingLog.setStatus(1);
                        tradingLog.setType(1);

                        if (order.getDistributionPrice() != null && order.getDistributionPrice() > 0) {
                            tradingLog.setAmount(ArithUtils.sub(order.getPrice(), order.getDistributionPrice()));
                        } else {
                            tradingLog.setAmount(order.getPrice());
                        }

                        tradingLog.setOrderNo(order.getOrderNo());
                        tradingLogRepository.save(tradingLog);

                        //商家订单金额到账
                        merchant.setBalance(ArithUtils.add(merchant.getBalance(), tradingLog.getAmount()));
                        merchant.setTotalOrderAmount(ArithUtils.add(merchant.getTotalOrderAmount(), tradingLog.getAmount()));
                        merchant.setTotalOrderNumber(merchant.getTotalOrderNumber() + 1);
                        userRepository.save(merchant);
                    }


                    if (order.getIsCloudStoreDelivery() == 1) {

                        List<BillOfLading> billOfLadings = queryChannelService.findAll(QBillOfLading.billOfLading.order.eq(order).and(QBillOfLading.billOfLading.status.eq(4)), BillOfLading.class);
                        for (BillOfLading billOfLading : billOfLadings) {
                            WebUser supplier = queryChannelService.findOne(QWebUser.webUser.id.eq(billOfLading.getSupplier().getId()), WebUser.class);
                            supplier.setBalance(ArithUtils.add(supplier.getBalance(), billOfLading.getPrice()));
                            userRepository.save(supplier);

                            TradingLog tradingLog2 = new TradingLog();
                            tradingLog2.setCreateTime(new Timestamp(System.currentTimeMillis()));
                            tradingLog2.setMerchant(supplier);
                            tradingLog2.setStatus(1);
                            tradingLog2.setType(6);
                            tradingLog2.setAmount(billOfLading.getPrice());
                            tradingLog2.setOrderNo(billOfLading.getOrderNo());
                            tradingLogRepository.save(tradingLog2);
                        }

                    }

                }
            }


        }
    }

    /**
     * 发货
     */
    public long delivery(Order params) {

        long id = 0;

        Order order = queryChannelService.findOne(QOrder.order.id.eq(params.getId()), Order.class);

        Express express = queryChannelService.findOne(QExpress.express.expressCompanyCode.eq(params.getExpressCode()), Express.class);
        Requires.notNull(express, "物流不存在");

        order.setExpressCompany(express.getName());
        order.setExpressesNo(params.getExpressesNo());
        order.setExpressCode(express.getExpressCompanyCode());

        order.setStatus(3);
        order.setDeliveryTime(new Timestamp(System.currentTimeMillis()));
        order.setIsCloudStoreDelivery(params.getIsCloudStoreDelivery());
        orderRepository.save(order);

        if (!Strings.isNullOrEmpty(params.getData())) {
            List<String> detailItems = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(params.getData());

            for (String detailItem : detailItems) {
                OrderDetail detail = queryChannelService.findOne(QOrderDetail.orderDetail.id.eq(Long.valueOf(detailItem.substring(0, detailItem.indexOf(":")))), OrderDetail.class);
                detail.setShippedQuantity(Integer.parseInt(detailItem.substring(detailItem.indexOf(":") + 1)));
                detailRepository.save(detail);
            }

        } else {

            for (OrderDetail detail : order.getDetails()) {
                detail.setShippedQuantity(detail.getQuantity());
                detailRepository.save(detail);
            }

        }


        //云仓发货单
        if (order.getIsCloudStoreDelivery() == 1) {
            List<String> cloudStoreItems = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(params.getNote());

            for (String item : cloudStoreItems) {
                CloudStoreGoods cloudStoreGoods = queryChannelService.findOne(QCloudStoreGoods.cloudStoreGoods.id.eq(Long.parseLong(item.substring(0, item.indexOf(":")))), CloudStoreGoods.class);

                BillOfLading billOfLading = new BillOfLading();
                billOfLading.setMerchant(order.getMerchant());
                billOfLading.setSupplier(cloudStoreGoods.getSupplier());
                billOfLading.setOrder(order);
                billOfLading.setDeliveryProvince(order.getDeliveryProvince());
                billOfLading.setDeliveryCity(order.getDeliveryCity());
                billOfLading.setDeliveryArea(order.getDeliveryArea());
                billOfLading.setDeliveryAddress(order.getDeliveryAddress());
                billOfLading.setDeliveryMobile(order.getDeliveryMobile());
                billOfLading.setDeliveryName(order.getDeliveryName());
                billOfLading.setCreateTime(new Timestamp(System.currentTimeMillis()));
                billOfLading.setShippingMethod(1);

                String data = cloudStoreGoods.getId() + ":" + item.substring(item.indexOf(":") + 1);
                billOfLading.setData(data);
                billLadingApplication.create(billOfLading);
                id = billOfLading.getId();
            }
        }

        Message message = new Message();
        message.setType(2);
        message.setMember(order.getMember());
        message.setOrderId(order.getId());
        message.setTitle("您有1笔订单已发货");
        message.setDigest("订单号:" + order.getOrderNo());
        message.setCreateTime(order.getDeliveryTime());

        if (order.getIsSupplier() == 1) {
            message.setPlatformType(1);
        }
        messageRepository.save(message);

        AliYunSmsService.send(order.getMember().getMobile(),
                PropertiesHelps.getValue("sign_name"),
                "SMS_211020801",
                ImmutableMap.of("merchantName", order.getMerchant().getUsername()));

        return id;
    }

    /**
     * 确认收货
     */
    public void receipt(Order order) {
        order.setStatus(4);
        order.setReceiptTime(new Timestamp(System.currentTimeMillis()));
        orderRepository.save(order);

        if (order.getIsCloudStoreDelivery() == 1) {
            List<BillOfLading> billOfLadings = queryChannelService.findAll("select b from BillOfLading b where b.order.id = :id and b.status = 3 ", ImmutableMap.of("id", order.getId()), BillOfLading.class);
            for (BillOfLading billOfLading : billOfLadings) {
                billOfLading.setStatus(4);
                billOfLading.setFinishTime(new Timestamp(System.currentTimeMillis()));
                billOfLading.setReceiptTime(new Timestamp(System.currentTimeMillis()));
                billOfLadingRepository.save(billOfLading);
            }
        }

        if (order.getDistributionOrder() != null && order.getDistributor() != null) {
            //确认收货分销订单
            try {
                DistributionSetting setting = distributionSettingApplication.findLastSetting();

                //启用分销
                if (BooleanUtils.isTrue(setting.getEnable())) {

                    double distributionPrice = 0;

                    Timestamp now = new Timestamp(System.currentTimeMillis());
                    int days = 7;
                    if (setting.getDistributionDuration() != null && setting.getDistributionDuration() > days) {
                        days = setting.getDistributionDuration();
                    }
                    Timestamp distributionTime = new Timestamp(System.currentTimeMillis() + (long) days * 3600 * 24 * 1000);

                    //如果购买人不是分销商
                    if (order.getMember().getDistributor() == null) {

                        //购买的是绑定分销商的商品，直接给上级和上上级分销
                        if (order.getMember().getFather() != null && order.getMember().getFather().getDistributor() != null && order.getMember().getFather().getDistributor().getId().equals(order.getDistributor().getId())) {

                            //一级分销,上级分销商获得
                            DistributionOrder dOrder1 = new DistributionOrder();
                            dOrder1.setCreateTime(new Timestamp(System.currentTimeMillis()));
                            dOrder1.setDistributor(order.getMember().getFather().getDistributor());
                            dOrder1.setDistrtionPay(1);
                            dOrder1.setOrder(order);
                            dOrder1.setScale(dOrder1.getDistributor().getLevel().getFirstLevelScale());
                            dOrder1.setSource(1);
                            dOrder1.setDistributionTime(distributionTime);
                            dOrder1.setMoney(computeDistributionOrderMoney(order, dOrder1.getScale()));
                            distributionPrice += dOrder1.getMoney();
                            distributionOrderRepository.save(dOrder1);

                            //二级分销 上上级分销商获得
                            if (order.getMember().getFather().getFather() != null && order.getMember().getFather().getFather().getDistributor() != null) {
                                DistributionOrder dOrder2 = new DistributionOrder();
                                dOrder2.setCreateTime(now);
                                dOrder2.setDistributor(order.getMember().getFather().getFather().getDistributor());
                                dOrder2.setDistrtionPay(1);
                                dOrder2.setOrder(order);
                                dOrder2.setScale(dOrder2.getDistributor().getLevel().getSecondLevelScale());
                                dOrder2.setSource(3);
                                dOrder2.setDistributionTime(distributionTime);
                                dOrder2.setMoney(computeDistributionOrderMoney(order, dOrder2.getScale()));
                                distributionPrice += dOrder2.getMoney();
                                distributionOrderRepository.save(dOrder2);
                            }
                        }

                        //购买的不是上级分销商的商品
                        if (order.getMember().getFather() == null || order.getMember().getFather().getDistributor() == null || !order.getMember().getFather().getDistributor().getId().equals(order.getDistributor().getId())) {

                            //分享人优先：业绩归分享人，先分佣给分享人，再按绑定的关系链进行分佣，即分销商D和分销商C获得分佣
                            if (setting.getPerformanceAttribution() == null || setting.getPerformanceAttribution() == 2) {
                                //一级分销 分享人获得
                                DistributionOrder dOrder1 = new DistributionOrder();
                                dOrder1.setCreateTime(now);
                                dOrder1.setDistributor(order.getDistributor());
                                dOrder1.setDistrtionPay(1);
                                dOrder1.setOrder(order);
                                dOrder1.setScale(dOrder1.getDistributor().getLevel().getFirstLevelScale());
                                dOrder1.setSource(5);
                                dOrder1.setDistributionTime(distributionTime);
                                dOrder1.setMoney(computeDistributionOrderMoney(order, dOrder1.getScale()));
                                distributionPrice += dOrder1.getMoney();
                                distributionOrderRepository.save(dOrder1);

                                //二级分销 上级分销商获得
                                if (order.getMember().getFather() != null && order.getMember().getFather().getDistributor() != null) {
                                    DistributionOrder dOrder2 = new DistributionOrder();
                                    dOrder2.setCreateTime(now);
                                    dOrder2.setDistributor(order.getMember().getFather().getDistributor());
                                    dOrder2.setDistrtionPay(1);
                                    dOrder2.setOrder(order);
                                    dOrder2.setScale(dOrder2.getDistributor().getLevel().getSecondLevelScale());
                                    dOrder2.setSource(1);
                                    dOrder2.setDistributionTime(distributionTime);
                                    dOrder2.setMoney(computeDistributionOrderMoney(order, dOrder2.getScale()));
                                    distributionPrice += dOrder2.getMoney();
                                    distributionOrderRepository.save(dOrder2);
                                }
                            }

                            //关系链优先：不管分享人是谁，业绩归邀请人，按绑定的关系链进行分佣，即分销商C和分销商B获得分佣
                            if (setting.getPerformanceAttribution() != null && setting.getPerformanceAttribution() == 1) {
                                //一级分销,上级分销商获得
                                if (order.getMember().getFather() != null && order.getMember().getFather().getDistributor() != null) {
                                    DistributionOrder dOrder1 = new DistributionOrder();
                                    dOrder1.setCreateTime(new Timestamp(System.currentTimeMillis()));
                                    dOrder1.setDistributor(order.getMember().getFather().getDistributor());
                                    dOrder1.setDistrtionPay(1);
                                    dOrder1.setOrder(order);
                                    dOrder1.setScale(dOrder1.getDistributor().getLevel().getFirstLevelScale());
                                    dOrder1.setSource(1);
                                    dOrder1.setDistributionTime(distributionTime);
                                    dOrder1.setMoney(computeDistributionOrderMoney(order, dOrder1.getScale()));
                                    distributionPrice += dOrder1.getMoney();
                                    distributionOrderRepository.save(dOrder1);

                                    //二级分销 上上级分销商获得
                                    if (order.getMember().getFather().getFather() != null && order.getMember().getFather().getFather().getDistributor() != null) {
                                        DistributionOrder dOrder2 = new DistributionOrder();
                                        dOrder2.setCreateTime(now);
                                        dOrder2.setDistributor(order.getMember().getFather().getFather().getDistributor());
                                        dOrder2.setDistrtionPay(1);
                                        dOrder2.setOrder(order);
                                        dOrder2.setScale(dOrder2.getDistributor().getLevel().getSecondLevelScale());
                                        dOrder2.setSource(3);
                                        dOrder2.setDistributionTime(distributionTime);
                                        dOrder2.setMoney(computeDistributionOrderMoney(order, dOrder2.getScale()));
                                        distributionPrice += dOrder2.getMoney();
                                        distributionOrderRepository.save(dOrder2);
                                    }
                                }
                            }

                        }

                    }

                    //如果购买人本身是分销商
                    if (order.getMember().getDistributor() != null) {

                        //后台未设置了分销商分销模式
                        if (setting.getType() == null) {

                            //分享人优先：业绩归分享人，先分佣给分享人，再按绑定的关系链进行分佣，即分销商D和分销商C获得分佣
                            if (setting.getPerformanceAttribution() == null || setting.getPerformanceAttribution() == 2) {

                                //一级分销 分享人获得
                                DistributionOrder dOrder1 = new DistributionOrder();
                                dOrder1.setCreateTime(now);
                                dOrder1.setDistributor(order.getDistributor());
                                dOrder1.setDistrtionPay(1);
                                dOrder1.setOrder(order);
                                dOrder1.setScale(dOrder1.getDistributor().getLevel().getFirstLevelScale());
                                dOrder1.setSource(5);
                                dOrder1.setDistributionTime(distributionTime);
                                dOrder1.setMoney(computeDistributionOrderMoney(order, dOrder1.getScale()));
                                distributionPrice += dOrder1.getMoney();
                                distributionOrderRepository.save(dOrder1);

                                //二级分销 上级分销商获得
                                if (order.getMember().getFather() != null && order.getMember().getFather().getDistributor() != null) {
                                    DistributionOrder dOrder2 = new DistributionOrder();
                                    dOrder2.setCreateTime(now);
                                    dOrder2.setDistributor(order.getMember().getFather().getDistributor());
                                    dOrder2.setDistrtionPay(1);
                                    dOrder2.setOrder(order);
                                    dOrder2.setScale(dOrder2.getDistributor().getLevel().getSecondLevelScale());
                                    dOrder2.setSource(2);
                                    dOrder2.setDistributionTime(distributionTime);
                                    dOrder2.setMoney(computeDistributionOrderMoney(order, dOrder2.getScale()));
                                    distributionPrice += dOrder2.getMoney();
                                    distributionOrderRepository.save(dOrder2);
                                }
                            }

                            //关系链优先：不管分享人是谁，业绩归邀请人，按绑定的关系链进行分佣，即分销商C和分销商B获得分佣
                            if (setting.getPerformanceAttribution() != null && setting.getPerformanceAttribution() == 1) {

                                //一级分销,上级分销商获得
                                if (order.getMember().getFather() != null && order.getMember().getFather().getDistributor() != null) {
                                    DistributionOrder dOrder1 = new DistributionOrder();
                                    dOrder1.setCreateTime(new Timestamp(System.currentTimeMillis()));
                                    dOrder1.setDistributor(order.getMember().getFather().getDistributor());
                                    dOrder1.setDistrtionPay(1);
                                    dOrder1.setOrder(order);
                                    dOrder1.setScale(dOrder1.getDistributor().getLevel().getFirstLevelScale());
                                    dOrder1.setSource(2);
                                    dOrder1.setDistributionTime(distributionTime);
                                    dOrder1.setMoney(computeDistributionOrderMoney(order, dOrder1.getScale()));
                                    distributionPrice += dOrder1.getMoney();
                                    distributionOrderRepository.save(dOrder1);

                                    //二级分销 上上级分销商获得
                                    if (order.getMember().getFather().getFather() != null && order.getMember().getFather().getFather().getDistributor() != null) {
                                        DistributionOrder dOrder2 = new DistributionOrder();
                                        dOrder2.setCreateTime(now);
                                        dOrder2.setDistributor(order.getMember().getFather().getFather().getDistributor());
                                        dOrder2.setDistrtionPay(1);
                                        dOrder2.setOrder(order);
                                        dOrder2.setScale(dOrder2.getDistributor().getLevel().getSecondLevelScale());
                                        dOrder2.setSource(4);
                                        dOrder2.setDistributionTime(distributionTime);
                                        dOrder2.setMoney(computeDistributionOrderMoney(order, dOrder2.getScale()));
                                        distributionPrice += dOrder2.getMoney();
                                        distributionOrderRepository.save(dOrder2);
                                    }
                                }
                            }
                        }

                        //后台设置分销商分销模式
                        if (setting.getType() != null) {

                            //自动模式，分销商必须购买自己分销店铺内的商品，或通过自己推荐的链接购买，才会给分销商自己分成
                            if (setting.getType() == 1) {

                                //如果购买的是自己店铺, 自己和上级
                                if (order.getDistributor().getId().equals(order.getMember().getDistributor().getId())) {

                                    DistributionOrder dOrder1 = new DistributionOrder();
                                    dOrder1.setCreateTime(now);
                                    dOrder1.setDistributor(order.getMember().getDistributor());
                                    dOrder1.setDistrtionPay(1);
                                    dOrder1.setOrder(order);
                                    dOrder1.setScale(dOrder1.getDistributor().getLevel().getFirstLevelScale());
                                    dOrder1.setSource(6);
                                    dOrder1.setDistributionTime(distributionTime);
                                    dOrder1.setMoney(computeDistributionOrderMoney(order, dOrder1.getScale()));
                                    distributionPrice += dOrder1.getMoney();
                                    distributionOrderRepository.save(dOrder1);

                                    if (order.getMember().getFather() != null && order.getMember().getFather().getDistributor() != null) {
                                        DistributionOrder dOrder2 = new DistributionOrder();
                                        dOrder2.setCreateTime(now);
                                        dOrder2.setDistributor(order.getMember().getFather().getDistributor());
                                        dOrder2.setDistrtionPay(1);
                                        dOrder2.setOrder(order);
                                        dOrder2.setScale(dOrder2.getDistributor().getLevel().getSecondLevelScale());
                                        dOrder2.setSource(2);
                                        dOrder2.setDistributionTime(distributionTime);
                                        dOrder2.setMoney(computeDistributionOrderMoney(order, dOrder2.getScale()));
                                        distributionPrice += dOrder2.getMoney();
                                        distributionOrderRepository.save(dOrder2);
                                    }

                                } else {

                                    //如果购买的不是自己店铺 上级和上上级
                                    if (order.getMember().getFather() != null && order.getMember().getFather().getDistributor() != null) {

                                        DistributionOrder dOrder1 = new DistributionOrder();
                                        dOrder1.setCreateTime(now);
                                        dOrder1.setDistributor(order.getMember().getFather().getDistributor());
                                        dOrder1.setDistrtionPay(1);
                                        dOrder1.setOrder(order);
                                        dOrder1.setScale(dOrder1.getDistributor().getLevel().getFirstLevelScale());
                                        dOrder1.setSource(2);
                                        dOrder1.setDistributionTime(distributionTime);
                                        dOrder1.setMoney(computeDistributionOrderMoney(order, dOrder1.getScale()));
                                        distributionPrice += dOrder1.getMoney();
                                        distributionOrderRepository.save(dOrder1);

                                        if (order.getMember().getFather().getFather() != null && order.getMember().getFather().getFather().getDistributor() != null) {
                                            DistributionOrder dOrder2 = new DistributionOrder();
                                            dOrder2.setCreateTime(now);
                                            dOrder2.setDistributor(order.getMember().getFather().getFather().getDistributor());
                                            dOrder2.setDistrtionPay(1);
                                            dOrder2.setOrder(order);
                                            dOrder2.setScale(dOrder2.getDistributor().getLevel().getSecondLevelScale());
                                            dOrder2.setSource(4);
                                            dOrder2.setDistributionTime(distributionTime);
                                            dOrder2.setMoney(computeDistributionOrderMoney(order, dOrder2.getScale()));
                                            distributionPrice += dOrder2.getMoney();
                                            distributionOrderRepository.save(dOrder2);
                                        }
                                    }
                                }

                            }

                            //内购模式，分销商购买所有的分销商品时，给分销商自己及自己的上级或推荐人分成
                            if (setting.getType() == 2) {

                                DistributionOrder dOrder1 = new DistributionOrder();
                                dOrder1.setCreateTime(now);
                                dOrder1.setDistributor(order.getMember().getDistributor());
                                dOrder1.setDistrtionPay(1);
                                dOrder1.setOrder(order);
                                dOrder1.setScale(dOrder1.getDistributor().getLevel().getFirstLevelScale());
                                dOrder1.setSource(6);
                                dOrder1.setDistributionTime(distributionTime);
                                dOrder1.setMoney(computeDistributionOrderMoney(order, dOrder1.getScale()));
                                distributionPrice += dOrder1.getMoney();
                                distributionOrderRepository.save(dOrder1);

                                if (order.getMember().getFather() != null && order.getMember().getFather().getDistributor() != null) {
                                    DistributionOrder dOrder2 = new DistributionOrder();
                                    dOrder2.setCreateTime(now);
                                    dOrder2.setDistributor(order.getMember().getFather().getDistributor());
                                    dOrder2.setDistrtionPay(1);
                                    dOrder2.setOrder(order);
                                    dOrder2.setScale(dOrder2.getDistributor().getLevel().getSecondLevelScale());
                                    dOrder2.setSource(2);
                                    dOrder2.setDistributionTime(distributionTime);
                                    dOrder2.setMoney(computeDistributionOrderMoney(order, dOrder2.getScale()));
                                    distributionPrice += dOrder2.getMoney();
                                    distributionOrderRepository.save(dOrder2);
                                }
                            }

                            //禁用内购模式，分销商购买所有的分销商品时，不给分销商自己分成，只给分销商的上级或推荐人分成
                            if (setting.getType() == 3) {

                                //一级分销,上级分销商获得
                                if (order.getMember().getFather() != null && order.getMember().getFather().getDistributor() != null) {
                                    DistributionOrder dOrder1 = new DistributionOrder();
                                    dOrder1.setCreateTime(now);
                                    dOrder1.setDistributor(order.getMember().getFather().getDistributor());
                                    dOrder1.setDistrtionPay(1);
                                    dOrder1.setOrder(order);
                                    dOrder1.setScale(dOrder1.getDistributor().getLevel().getFirstLevelScale());
                                    dOrder1.setSource(1);
                                    dOrder1.setDistributionTime(distributionTime);
                                    dOrder1.setMoney(computeDistributionOrderMoney(order, dOrder1.getScale()));
                                    distributionPrice += dOrder1.getMoney();
                                    distributionOrderRepository.save(dOrder1);

                                    //二级分销 上上级分销商获得
                                    if (order.getMember().getFather().getFather() != null && order.getMember().getFather().getFather().getDistributor() != null) {
                                        DistributionOrder dOrder2 = new DistributionOrder();
                                        dOrder2.setCreateTime(now);
                                        dOrder2.setDistributor(order.getMember().getFather().getFather().getDistributor());
                                        dOrder2.setDistrtionPay(1);
                                        dOrder2.setOrder(order);
                                        dOrder2.setScale(dOrder2.getDistributor().getLevel().getSecondLevelScale());
                                        dOrder2.setSource(3);
                                        dOrder2.setDistributionTime(distributionTime);
                                        dOrder2.setMoney(computeDistributionOrderMoney(order, dOrder2.getScale()));
                                        distributionPrice += dOrder2.getMoney();
                                        distributionOrderRepository.save(dOrder2);
                                    }
                                }
                            }
                        }
                    }

                    order.setDistributionPrice(ArithUtils.roundHalfUp(distributionPrice, 2));
                }
            } catch (Exception e) {
                log.error("[生成分销订单异常]", e);
            }
        } else if (order.getLiveSession() != null) {
            //确认收货直播订单

            LiveOrder liveOrder = new LiveOrder();
            liveOrder.setCreateTime(new Timestamp(System.currentTimeMillis()));
            liveOrder.setAnchor(order.getLiveSession().getAnchor());
            liveOrder.setOrder(order);
            liveOrder.setSendStatus(1);

            LiveGoodsAnchor liveGoodsAnchor = queryChannelService.findOne(QLiveGoodsAnchor.liveGoodsAnchor.anchor.eq(liveOrder.getAnchor()).and(QLiveGoodsAnchor.liveGoodsAnchor.goods.eq(order.getDetails().get(0).getSku().getGoods())), LiveGoodsAnchor.class);
            liveOrder.setScale(liveGoodsAnchor.getLiveGoods().getGuaranteeScale());
            liveOrder.setMoney(computeLiveOrderMoney(order, liveOrder.getAnchor()));

            LiveSetting liveSetting = queryChannelService.queryOneEntity("select * from live_setting order by id desc limit 1", new HashMap<>(), LiveSetting.class);
            int days = 7;
            if (liveSetting != null && liveSetting.getDistributionDuration() != null && liveSetting.getDistributionDuration() > 7) {
                days = liveSetting.getDistributionDuration();
            }

            liveOrder.setSendTime(DateUtil.offsetDay(new Date(), days).toTimestamp());
            liveOrder.setRealSendTime(null);

            liveOrderRepository.save(liveOrder);


            LiveBalanceRecord record = new LiveBalanceRecord();
            record.setAnchor(liveOrder.getAnchor());
            record.setType(3);
            record.setCreateTime(new Timestamp(System.currentTimeMillis()));
            record.setMoney(liveOrder.getMoney());
            record.setBalance(liveOrder.getAnchor().getLiveBalance());
            liveBalanceRecordRepository.save(record);

        }


    }

    /**
     * 商家的采购订单确认收货（将采购的商品入库）
     */
    public void purchaseReceipt(Order order) throws Exception {
        order.setStatus(4);
        order.setReceiptTime(new Timestamp(System.currentTimeMillis()));
        orderRepository.save(order);

        //开始
        List<OrderDetail> orderDetails = order.getDetails();
        Map<Long, Goods> uniquenGoodses = Maps.newHashMap();

        for (OrderDetail orderDetail : orderDetails) {  //过滤重复的商品
            uniquenGoodses.put(orderDetail.getSku().getGoods().getId(), orderDetail.getSku().getGoods());
        }

        for (Map.Entry<Long, Goods> entry : uniquenGoodses.entrySet()) {
            Goods supplierGoods = queryChannelService.findOne(QGoods.goods.id.eq(entry.getKey()), Goods.class);

            Goods goods = new Goods();
            BeanUtils.copyProperties(goods, supplierGoods);

            List<GoodsImage> images = goods.getImages();
            List<GoodsSaleAttribute> saleAttributes = goods.getSaleAttributes();

            goods.setMerchant(order.getMember());
            goods.setIsSupplier(0);
            goods.setSalesVolume(0);
            goods.setIssuingGoods(supplierGoods);

            goods.setStore(0);
            goods.setStatus(1);
            goods.setImages(null);
            goods.setSkus(null);
            goods.setParamses(null);
            goods.setSaleAttributes(null);
            goods.setId(0);
            goods.setIsIssuingType(0);
            goods.setCreateTime(new Timestamp(System.currentTimeMillis()));
            goods.setIsSupplier(0);
            goods.setRecommendSupplier(false);
            goods.setRecommend(false);

            goodsRepository.save(goods);

            List<GoodsSku> skus = Lists.newArrayList();

            for (OrderDetail orderDetail : orderDetails) {
                if (orderDetail.getSku().getGoods().getId() == supplierGoods.getId()) {
                    GoodsSku sku = orderDetail.getSku();
                    sku.setStore(orderDetail.getShippedQuantity());
                    skus.add(sku);
                }
            }

            for (GoodsImage item : images) {
                GoodsImage image = new GoodsImage();
                image.setCreateTime(item.getCreateTime());
                image.setGoods(goods);
                image.setMerchant(goods.getMerchant());
                image.setName(item.getName());
                imageRepository.save(image);
            }

            for (GoodsSaleAttribute item : saleAttributes) {

                GoodsAttribute oldAttr = queryChannelService.findOne(QGoodsAttribute.goodsAttribute.id.eq(item.getAttributeId()), GoodsAttribute.class);
                GoodsAttribute attr = queryChannelService.findOne(QGoodsAttribute.goodsAttribute.issuingSupplierAttributeId.eq(oldAttr.getId()), GoodsAttribute.class);

                if (null == attr) {
                    attr = new GoodsAttribute();
                    org.springframework.beans.BeanUtils.copyProperties(oldAttr, attr);
                    attr.setId(0);
                    attr.setType(2);
                    attr.setStatus(1);
                    attr.setMerchant(goods.getMerchant());
                    attr.setAttributes(null);
                    attr.setIssuingSupplierAttributeId(oldAttr.getId());
                    attributeRepository.save(attr);
                }


                GoodsSaleAttribute attribute = new GoodsSaleAttribute();
                attribute.setGoods(goods);
                attribute.setMerchant(goods.getMerchant());
                attribute.setCreateTime(item.getCreateTime());
                attribute.setAttributeId(attr.getId());
                attribute.setName(attr.getName());
                saleAttributeRepository.save(attribute);

                for (GoodsSaleAttribute childrenItem : item.getValues()) {

                    GoodsAttribute oldAttr2 = queryChannelService.findOne(QGoodsAttribute.goodsAttribute.id.eq(childrenItem.getAttributeId()), GoodsAttribute.class);
                    GoodsAttribute attr2 = queryChannelService.findOne(QGoodsAttribute.goodsAttribute.issuingSupplierAttributeId.eq(oldAttr2.getId()), GoodsAttribute.class);

                    if (null == attr2) {
                        attr2 = new GoodsAttribute();
                        org.springframework.beans.BeanUtils.copyProperties(oldAttr2, attr2);
                        attr2.setId(0);
                        attr2.setType(2);
                        attr2.setStatus(1);
                        attr2.setParent(attr);
                        attr2.setMerchant(goods.getMerchant());
                        attr2.setAttributes(null);
                        attr2.setIssuingSupplierAttributeId(oldAttr2.getId());
                        attributeRepository.save(attr2);
                    }

                    GoodsSaleAttribute saleAttribute = new GoodsSaleAttribute();
                    saleAttribute.setMerchant(childrenItem.getMerchant());
                    saleAttribute.setCreateTime(childrenItem.getCreateTime());
                    saleAttribute.setAttributeId(attr2.getId());
                    saleAttribute.setName(attr2.getName());
                    saleAttribute.setParent(attribute);
                    saleAttributeRepository.save(saleAttribute);

                }


            }


            for (GoodsSku item : skus) {
                GoodsSku sku = new GoodsSku();
                sku.setGoods(goods);
                sku.setMerchant(goods.getMerchant());
                sku.setCode(item.getCode());
                sku.setSkuNames(item.getSkuNames());
                sku.setStore(item.getStore());
                sku.setPrice(item.getPrice());
                sku.setIssuingSku(item);


                GoodsAttribute attribute1 = queryChannelService.findOne(QGoodsAttribute.goodsAttribute.issuingSupplierAttributeId.eq(item.getAttribute1().getId()), GoodsAttribute.class);
                if (null != item.getAttribute2()) {
                    GoodsAttribute attribute2 = queryChannelService.findOne(QGoodsAttribute.goodsAttribute.issuingSupplierAttributeId.eq(item.getAttribute2().getId()), GoodsAttribute.class);
                    sku.setAttribute2(attribute2);
                }

                sku.setAttribute1(attribute1);

                if (sku.getAttribute2() != null) {
                    sku.setSkuNo(attribute1.getId() + "-" + sku.getAttribute2().getId());
                } else {
                    sku.setSkuNo(attribute1.getId() + "");
                }

                skuRepository.save(sku);
            }

            int store = 0;
            for (GoodsSku goodsSku : skus) {
                store = store + goodsSku.getStore();
            }

            goods.setStore(store);
            goodsRepository.save(goods);
        }

    }

    /**
     * 微信支付
     */
    public void wechatPay(String payNo, Order order) {
        order.setPayNo(payNo);
        order.setPayMethod(1);
        orderRepository.save(order);
    }

    /**
     * 微信支付拼团订单
     */
    public void wechatPayGroupBooking(String payNo, GroupBookingOrder order) {
        order.setPayNo(payNo);
        order.setPayMethod(1);
        groupBookingOrderRepository.save(order);
    }

    /**
     * 微信支付成功
     */
    public void paySuccess(List<Order> orders) {

        for (Order order : orders) {

            //如果是申请分销商订单，支付成功后，立即成为相应等级的分销商,并且该订单不允许售后
            if (order.getApplyDistributor() != null && order.getApplyDistributor() > 0 && order.getApplyDistributor() <= 5) {
                WebUser member = order.getMember();
                DistributionCheck distributionCheck = new DistributionCheck().setCreateTime(new Timestamp(System.currentTimeMillis()));
                distributionCheck.setCheckTime(distributionCheck.getCreateTime());
                distributionCheck.setMember(member);
                distributionCheck.setCheckStatus(2);
                distributionCheck.setCheckNote("系统默认通过审核");
                distributionCheck.setDistributorLevel(queryChannelService.findOne(QDistributorLevel.distributorLevel.level.eq(order.getApplyDistributor()), DistributorLevel.class));
                distributionCheck.setActivationFlag(false);
                distributionCheckRepository.save(distributionCheck);
            }

            if (order.getPayMethod() == 1 || order.getPayMethod() == 2) {    //微信支付,支付宝支付

                order.setPayStatus(1);
                order.setPayTime(new Timestamp(System.currentTimeMillis()));
                order.setStatus(2);

                //赠品活动订单，给赠品减库存
                if (order.getMarketingType() == 1) {

                    List<Goods> giftGoodses = queryChannelService.findAll("select g.goods from GiftGoods g where g.gift.id = :id ", ImmutableMap.of("id", order.getGiftActivity().getId()), Goods.class);

                    for (Goods giftGoodse : giftGoodses) {
                        giftGoodse.setStore(giftGoodse.getStore() - 1 == 0 ? 0 : giftGoodse.getStore() - 1);
                        giftGoodse.setSalesVolume(giftGoodse.getSalesVolume() + 1);
                        goodsRepository.save(giftGoodse);

                        GoodsSku sku = giftGoodse.getSkus().get(0);
                        sku.setStore(sku.getStore() - 1);
                        skuRepository.save(sku);
                    }
                }

            }


            if (order.getPayMethod() == 3 && order.getIsSupplier() == 1) {    //钱包余额组合微信支付

                order.setPayStatus(1);
                order.setPayTime(new Timestamp(System.currentTimeMillis()));
                order.setStatus(2);

                WebUser merchant = queryChannelService.findOne(QWebUser.webUser.eq(order.getMember()), WebUser.class);
                WebUser supplier = queryChannelService.findOne(QWebUser.webUser.eq(order.getMerchant()), WebUser.class);


                merchant.setBalance(ArithUtils.sub(merchant.getBalance(), order.getBlancePrice()));
                userRepository.save(merchant);

                supplier.setBalance(ArithUtils.add(supplier.getBalance(), order.getPrice()));
                userRepository.save(supplier);

                TradingLog tradingLog = new TradingLog();
                tradingLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
                tradingLog.setMerchant(merchant);
                tradingLog.setStatus(0);
                tradingLog.setType(2);
                tradingLog.setAmount(order.getBlancePrice());
                tradingLog.setOrderNo(order.getOrderNo());
                tradingLogRepository.save(tradingLog);

                TradingLog tradingLog2 = new TradingLog();
                tradingLog2.setCreateTime(new Timestamp(System.currentTimeMillis()));
                tradingLog2.setMerchant(supplier);
                tradingLog2.setStatus(1);
                tradingLog2.setType(1);
                tradingLog2.setAmount(order.getPrice());
                tradingLog2.setOrderNo(order.getOrderNo());
                tradingLogRepository.save(tradingLog2);


            }

            if (order.getDeliveryType() == 2) {
                List<OrderDetail> details = order.getDetails();
                for (OrderDetail detail : details) {
                    if (detail.getQuantity() - detail.getDeliveryQuantity() > 0) {

                        CloudStoreGoods cloudStoreGoods = new CloudStoreGoods();
                        cloudStoreGoods.setMerchant(order.getMember());
                        cloudStoreGoods.setSupplier(order.getMerchant());
                        cloudStoreGoods.setQuantity(detail.getQuantity() - detail.getDeliveryQuantity());
                        cloudStoreGoods.setGoods(detail.getSku().getGoods());
                        cloudStoreGoods.setSku(detail.getSku());
                        cloudStoreGoods.setStatus(1);
                        cloudStoreGoods.setCreateTime(new Timestamp(System.currentTimeMillis()));

                        cloudStoreRepository.save(cloudStoreGoods);

                    }
                }
            }


        }
        orderRepository.save(orders);

        for (Order order : orders) {

            try {

                if (order.getMember() != null && StrUtil.isNotBlank(order.getMember().getMobile())) {
                    AliYunSmsService.send(order.getMember().getMobile(),
                            PropertiesHelps.getValue("sign_name"),
                            "SMS_211025754",
                            ImmutableMap.of("orderAmount", String.valueOf(order.getPrice()), "orderNo", order.getOrderNo()));
                }

                if (order.getIsIssuingType() == 1) {
                    if (order.getMerchant() != null && StrUtil.isNotBlank(order.getMerchant().getMobile())) {
                        AliYunSmsService.send(order.getMerchant().getMobile(),
                                PropertiesHelps.getValue("sign_name"),
                                "SMS_211025759",
                                ImmutableMap.of("orderAmount", String.valueOf(order.getPrice()), "orderNo", order.getOrderNo()));
                    }
                } else {
                    if (order.getMerchant() != null && StrUtil.isNotBlank(order.getMerchant().getMobile())) {
                        AliYunSmsService.send(order.getMerchant().getMobile(),
                                PropertiesHelps.getValue("sign_name"),
                                "SMS_211000770",
                                ImmutableMap.of("orderAmount", String.valueOf(order.getPrice()), "orderNo", order.getOrderNo()));
                    }
                }

                if (order.getIsSupplier() == 1) {
                    if (order.getMember() != null && StrUtil.isNotBlank(order.getMember().getMobile())) {
                        AliYunSmsService.send(order.getMember().getMobile(),
                                PropertiesHelps.getValue("sign_name2"),
                                "SMS_211025754",
                                ImmutableMap.of("orderAmount", String.valueOf(order.getPrice()), "orderNo", order.getOrderNo()));
                    }

                    if (order.getSupplier() != null && StrUtil.isNotBlank(order.getSupplier().getMobile())) {
                        AliYunSmsService.send(order.getSupplier().getMobile(),
                                PropertiesHelps.getValue("sign_name2"),
                                "SMS_211000770",
                                ImmutableMap.of("orderAmount", String.valueOf(order.getPrice()), "orderNo", order.getOrderNo()));
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 计算分销订单分销金额
     *
     * @param order 订单
     * @param scale 获得分销的分销商分销比例(可能是一级分销，可能是二级分销)
     */
    private double computeDistributionOrderMoney(Order order, double scale) {
        GoodsSku sku = order.getDetails().get(0).getSku();
        Goods goods = sku.getGoods();
        DistributionGoods distributionGoods = queryChannelService.queryOneEntity("select * from distribution_goods where goods_id = :gid", ImmutableMap.of("gid", goods.getId()), DistributionGoods.class);

        double s = distributionGoods.getGuaranteeScale() == null ? 0 : distributionGoods.getGuaranteeScale();
        return ArithUtils.roundHalfUp(ArithUtils.mul(ArithUtils.mul(sku.getPrice(), (1 - s)), scale), 2);
    }

    /**
     * 计算直播订单分销金额
     *
     * @param order 订单
     */
    private double computeLiveOrderMoney(Order order, WebUser anchor) {

        GoodsSku sku = order.getDetails().get(0).getSku();
        Goods goods = sku.getGoods();

        LiveGoodsAnchor liveGoodsAnchor = queryChannelService.queryOneEntity("select * from live_goods_anchor where goods_id = :gid and anchor_id = :aid limit 1",
                ImmutableMap.of("gid", goods.getId(), "aid", anchor.getId()), LiveGoodsAnchor.class);
        LiveGoods liveGoods = liveGoodsAnchor.getLiveGoods();

        return NumberUtil.roundDown(NumberUtil.mul(sku.getPrice(), liveGoods.getGuaranteeScale()), 2).doubleValue();

    }

    /**
     * 自动取消一小时未支付的订单（每分钟执行）
     */
    public void autoCancelOrders() throws Exception {
        List<Order> orders = queryChannelService.findAll("select o from Order o where o.status = 1 and o.marketingType = 0 ", Order.class);
        for (Order order : orders) {
            long diff = (System.currentTimeMillis() - order.getCreateTime().getTime()) / 1000 / 60;
            if (diff >= 60) {
                cancel(order, "未在60分钟内完成支付，系统自动取消");

                //如果使用了购物卡，返还购物卡
                if (order.getHavaShoppingCardRecord() == 1) {
                    recoverShoppingCard(order);
                }
            }
        }
    }

    /**
     * 分佣订单定时处理(分销分佣)
     */
    public void autoPayDistributionOrder() {
        List<DistributionOrder> distributionOrders = queryChannelService.findAll(QDistributionOrder.distributionOrder.distrtionPay.eq(1).and(QDistributionOrder.distributionOrder.distributionTime.before(new Timestamp(System.currentTimeMillis()))), DistributionOrder.class);
        for (DistributionOrder order : distributionOrders) {
            Distributor distributor = queryChannelService.findOne(QDistributor.distributor.id.eq(order.getDistributor().getId()), Distributor.class);
            distributor.setBalance(ArithUtils.roundHalfUp(distributor.getBalance() + order.getMoney(), 2));
            distributorRepository.saveAndFlush(distributor);
            order.setDistrtionPay(2);
            order.setSendTime(new Timestamp(System.currentTimeMillis()));
        }
        distributionOrderRepository.save(distributionOrders);
    }

    /**
     * 分佣订单定时处理(直播分佣)
     */
    public void autoPayLiveOrder() {
        List<LiveOrder> liveOrders = queryChannelService.findAll(QLiveOrder.liveOrder.sendStatus.eq(1).and(QLiveOrder.liveOrder.sendTime.before(new Timestamp(System.currentTimeMillis()))), LiveOrder.class);
        for (LiveOrder liveOrder : liveOrders) {
            if (liveOrder.getOrder().getIsAfterSale() != 0) {
                liveOrder.setSendStatus(3);
                continue;
            }
            long userId = liveOrder.getAnchor().getId();
            synchronized (SyncLock.getLock(String.valueOf(userId))) {
                WebUser user = queryChannelService.findOne(WebUser.class, userId);
                user.setLiveBalance(NumberUtil.roundDown(NumberUtil.add(user.getBalance(), liveOrder.getMoney()), 2).doubleValue());
                userRepository.save(user);

                LiveBalanceRecord record = new LiveBalanceRecord();
                record.setAnchor(user);
                record.setType(1);
                record.setCreateTime(new Timestamp(System.currentTimeMillis()));
                record.setMoney(liveOrder.getMoney());
                record.setBalance(user.getLiveBalance());
                liveBalanceRecordRepository.save(record);

            }
            liveOrder.setSendStatus(2);
            liveOrder.setRealSendTime(new Timestamp(System.currentTimeMillis()));
        }
        liveOrderRepository.save(liveOrders);
    }


    /**
     * 订单自动取消时，返还购物卡金额
     *
     * @param order 订单
     */
    private void recoverShoppingCard(Order order) {

        ShoppingCardRecord record = order.getShoppingCardRecord();

        if (record == null) {

            return;
        }

        //还原购物卡的金额
        record.setBalance(ArithUtils.add(record.getBalance(), order.getShoppingCardMoney()));

        //还原可使用的状态
        if (record.getStatus() == 2) {
            record.setStatus(1);
        }
        shoppingCardRecordRepository.save(record);

        //删除相应的消费记录
        ShoppingCardRecordConsume consume = queryChannelService.findOne(QShoppingCardRecordConsume.shoppingCardRecordConsume.order.id.eq(order.getId()), ShoppingCardRecordConsume.class);
        if (consume != null) {
            shoppingCardRecordConsumeRepository.delete(consume);
        }
    }

    /**
     * 订单状态更新处理（每天凌晨0点处理）
     */
    public void autoOrderDispose() {

        //发货后7天自动确认收货；
        List<Order> nonReceiptOrders = queryChannelService.queryAllEntity("SELECT * FROM mall_order where DATE_SUB(CURDATE(), INTERVAL 7 DAY) >= date(deliveryTime) and status = 3 and isAfterSale = 0", new HashMap<>(), Order.class);
        for (Order order : nonReceiptOrders) {
            receipt(order);
        }

        //收货后7天自动评价、分账、交易流水、积分；
        List<Order> nonCommentOrders = queryChannelService.queryAllEntity("SELECT * FROM mall_order where DATE_SUB(CURDATE(), INTERVAL 7 DAY) >= date(receiptTime) and status = 4 and isAfterSale = 0", new HashMap<>(), Order.class);
        for (Order order : nonCommentOrders) {

            List<OrderDetail> details = queryChannelService.findAll(QOrderDetail.orderDetail.order.id.eq(order.getId()), OrderDetail.class);
            WebUser member = order.getMember();

            for (OrderDetail detail : details) {

                GoodsComment comment = new GoodsComment();
                comment.setContent("系统默认好评");
                comment.setStarLever(5);
                comment.setGoods(detail.getSku().getGoods());

                comment(member, comment, detail);
            }
        }

    }

    /**
     * 修改订单总价
     */
    public void modifyAmount(Order params) {
        Order order = queryChannelService.findOne(QOrder.order.id.eq(params.getId()), Order.class);
        order.setMoney(params.getPrice());
        orderRepository.save(order);
    }

    /**
     * 提货
     */
    public void shipping(Order one) {
        receipt(one);
    }

    /**
     * 提交拼团订单
     */
    public GroupBookingOrder submitGroupBookingOrder(WebUser member, OrderDTO orderDTO) {

        GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(orderDTO.getDetails().get(0).getId()), GoodsSku.class);

        WebUser merchant = queryChannelService.findOne(QWebUser.webUser.id.eq(sku.getGoods().getMerchant().getId()), WebUser.class);

        GroupBooking groupBooking = new GroupBooking();

        //开团
        if (orderDTO.getId() == 0) {

            groupBooking.setCreateTime(new Timestamp(System.currentTimeMillis()));
            groupBooking.setSku(sku);
            groupBooking.setGoodsName(sku.getGoods().getName());
            groupBooking.setDefaultImage(sku.getGoods().getDefaultImage());
            groupBooking.setGroupBookingCondition(sku.getGoods().getGroupBookingCondition());
            groupBooking.setMember(member);
            groupBooking.setMerchant(merchant);
            groupBooking.setStatus(0);
            String groupBookingNo = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + merchant.getId() + member.getId();
            groupBooking.setGroupBookingNo(groupBookingNo);
            groupBooking.setProductNo(sku.getGoods().getGoodsNo());
            groupBooking.setEndTime(sku.getGoods().getGroupBookingEndTime());
            groupBookingRepository.save(groupBooking);
        }

        //参团
        if (orderDTO.getId() > 0) {
            groupBooking = queryChannelService.findOne(QGroupBooking.groupBooking.id.eq(orderDTO.getId()), GroupBooking.class);
            for (GroupBookingOrder groupBookingOrder : groupBooking.getDetails()) {
                if (groupBookingOrder.getMember().getId() == member.getId() && groupBookingOrder.getStatus() != 5) {
                    throw new InterfaceException("该团您已参与，请不要重复参与");
                }
            }
            groupBookingRepository.save(groupBooking);
        }

        GroupBookingOrder order = new GroupBookingOrder();

        String orderNo = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + merchant.getId() + member.getId() + groupBooking.getId();
        order.setOrderNo(orderNo);
        order.setGroupBooking(groupBooking);
        order.setMember(member);
        order.setMerchant(merchant);
        order.setSku(sku);
        order.setCreateTime(new Timestamp(System.currentTimeMillis()));
        order.setDeliveryName(orderDTO.getDeliveryName());
        order.setDeliveryProvince(orderDTO.getDeliveryProvince());
        order.setDeliveryCity(orderDTO.getDeliveryCity());
        order.setDeliveryArea(orderDTO.getDeliveryArea());
        order.setDeliveryAddress(orderDTO.getDeliveryAddress());
        order.setDeliveryMobile(orderDTO.getDeliveryMobile());
        order.setShippingMethod(orderDTO.getShippingMethod());
        order.setPayStatus(2);
        order.setInvoiceTFN(orderDTO.getInvoiceTFN());
        order.setInvoiceTitle(orderDTO.getInvoiceTitle());
        order.setHaveInvoice(orderDTO.getHaveInvoice());
        order.setInvoiceTitleType(orderDTO.getInvoiceTitleType());
        order.setInvoiceType(orderDTO.getInvoiceType());
        order.setQuantity(orderDTO.getDetails().get(0).getQuantity());

        if (orderDTO.getId() == 0) {
            order.setType(1);
        } else {
            order.setType(2);
        }
        order.setStatus(1);
        order.setSpecs(sku.getAttribute1().getName() + " " + (null != sku.getAttribute2() ? sku.getAttribute2().getName() : ""));

        groupBookingOrderRepository.save(order);
        double freightPrice = 0;

        //运费计算
        double price = ArithUtils.mul(sku.getGroupBookingPrice(), order.getQuantity());     //单价 * 数量

        if (price < 0) {
            price = 0;
        }

        order.setGoodsSubtotalPrice(price);
        order.setShippingMethod(orderDTO.getShippingMethod());


        if (sku.getGoods().getPostageType() == 1) {     //走运费模板

            MerchantFreight freight = queryChannelService.findOne(QMerchantFreight.merchantFreight.city.eq(order.getDeliveryCity()).and(QMerchantFreight.merchantFreight.merchant.eq(merchant).and(QMerchantFreight.merchantFreight.template.id.eq(sku.getGoods().getFreightTemplate().getId()))), MerchantFreight.class);

            MerchantFreightTemplate template = queryChannelService.findOne(QMerchantFreightTemplate.merchantFreightTemplate.id.eq(sku.getGoods().getFreightTemplate().getId()), MerchantFreightTemplate.class);

            //按重量
            if (template.getType() == 1) {
                double gram = ArithUtils.mul(sku.getGoods().getGram(), order.getQuantity());//总重量
                if (null != freight) {   //拿到了模板内设置的区域运费
                    if (gram <= freight.getFirstWeight()) {
                        freightPrice = freight.getFirstWeightAmount();
                    } else {
                        freightPrice = ArithUtils.add(freight.getFirstWeightAmount(), ArithUtils.mul(ArithUtils.div(ArithUtils.sub(gram, freight.getFirstWeight()), freight.getOtherWeight(), 2), freight.getOtherWeightAmount()));
                    }
                } else {
                    if (gram <= template.getDefaultWeight()) {
                        freightPrice = template.getDefaultWeightAmount();
                    } else {
                        freightPrice = ArithUtils.add(template.getDefaultWeightAmount(), ArithUtils.mul(ArithUtils.div(ArithUtils.sub(gram, template.getDefaultWeight()), template.getDefaultAddWeight(), 2), template.getDefaultAddWeightAmount()));
                    }
                }
            }

            //按件
            if (template.getType() == 2) {
                if (null != freight) {
                    if (order.getQuantity() <= freight.getFirstPiece()) {
                        freightPrice = freight.getFirstPieceAmount();
                    } else {
                        freightPrice = ArithUtils.add(freight.getFirstPieceAmount(), ArithUtils.mul(ArithUtils.sub(order.getQuantity(), freight.getFirstPiece()), freight.getOtherPieceAmount()));
                    }
                } else {
                    if (order.getQuantity() <= template.getDefaultPiece()) {
                        freightPrice = template.getDefaultPieceAmount();
                    } else {
                        freightPrice = ArithUtils.add(template.getDefaultPieceAmount(), ArithUtils.mul(ArithUtils.sub(order.getQuantity(), template.getDefaultPiece()), template.getDefaultAddPieceAmount()));
                    }
                }
            }
        } else if (sku.getGoods().getPostageType() == 2) {      //包邮
            freightPrice = ArithUtils.add(freightPrice, 0);
        } else if (sku.getGoods().getPostageType() == 3) {       //指定运费
            freightPrice = ArithUtils.add(freightPrice, ArithUtils.mul(sku.getGoods().getPostage(), order.getQuantity()));
        }

        if (orderDTO.getShippingMethod() == 2) {   //自提
            freightPrice = 0;
            order.setShippingAddress(order.getMerchant().getWarehouseAddress());
        }

        order.setFreightPrice(freightPrice);
        order.setPrice(ArithUtils.add(freightPrice, order.getGoodsSubtotalPrice()));
        groupBookingOrderRepository.save(order);


        //减库存，加销量
        sku.setGroupBookingStore(Math.max(sku.getGroupBookingStore() - order.getQuantity(), 0));
        sku.setStore(Math.max(sku.getStore() - order.getQuantity(), 0));
        skuRepository.save(sku);

        Goods goods = queryChannelService.findOne(QGoods.goods.eq(sku.getGoods()), Goods.class);
        goods.setGroupBookingStore(Math.max(goods.getGroupBookingStore() - order.getQuantity(), 0));
        goods.setGroupBookingSalesVolume(goods.getGroupBookingSalesVolume() + order.getQuantity());
        goods.setStore(Math.max(goods.getStore() - order.getQuantity(), 0));

        if (goods.getGroupBookingStore() == 0) {
            goods.setGroupBookingStatus(6);
        }

        goodsRepository.save(goods);


        return order;

    }

    /**
     * 拼团订单支付成功
     */
    public void groupBookingOrderWechatPaySuccess(GroupBookingOrder order) {
        order.setPayStatus(1);
        order.setPayMethod(1);
        order.setPayTime(new Timestamp(System.currentTimeMillis()));
        order.setStatus(2);
        groupBookingOrderRepository.save(order);

        GroupBooking groupBooking = queryChannelService.findOne(QGroupBooking.groupBooking.id.eq(order.getGroupBooking().getId()), GroupBooking.class);
        groupBooking.setGroupBookingTotal(groupBooking.getGroupBookingTotal() + 1);

        if (groupBooking.getGroupBookingTotal() == groupBooking.getGroupBookingCondition()) {
            groupBooking.setStatus(2);
            groupBookingRepository.save(groupBooking);
            groupBookingFinishTransferOrder(groupBooking);
        } else {
            groupBooking.setStatus(1);
        }
        groupBookingRepository.save(groupBooking);
    }

    /**
     * 拼团成功，将成团的拼团订单转化为普通订单
     */
    private void groupBookingFinishTransferOrder(GroupBooking groupBooking) {

        List<GroupBookingOrder> orders = queryChannelService.findAll(QGroupBookingOrder.groupBookingOrder.groupBooking.eq(groupBooking).and(QGroupBookingOrder.groupBookingOrder.status.eq(2)), GroupBookingOrder.class);
        for (GroupBookingOrder item : orders) {

            item.setStatus(3);
            groupBookingOrderRepository.save(item);

            Order order = new Order();
            order.setOrderNo(item.getOrderNo());
            order.setMember(item.getMember());
            order.setMerchant(item.getMerchant());
            order.setCreateTime(item.getCreateTime());
            order.setPrice(item.getPrice());
            order.setFreightPrice(item.getFreightPrice());
            order.setGoodsSubtotalPrice(item.getGoodsSubtotalPrice());
            order.setShippingMethod(item.getShippingMethod());
            order.setShippingAddress(item.getShippingAddress());
            order.setGoodsQuantity(item.getQuantity());
            order.setStatus(2);
            order.setMarketingType(2);
            order.setPayStatus(1);
            order.setPayTime(item.getPayTime());
            order.setPayMethod(item.getPayMethod());
            order.setPayNo(item.getPayNo());
            order.setDeliveryName(item.getDeliveryName());
            order.setDeliveryProvince(item.getDeliveryProvince());
            order.setDeliveryCity(item.getDeliveryCity());
            order.setDeliveryArea(item.getDeliveryArea());
            order.setDeliveryAddress(item.getDeliveryAddress());
            order.setDeliveryMobile(item.getDeliveryMobile());
            order.setInvoiceType(item.getInvoiceType());
            order.setHaveInvoice(item.getHaveInvoice());
            order.setInvoiceTitleType(item.getInvoiceTitleType());
            order.setInvoiceTitle(item.getInvoiceTitle());
            order.setInvoiceTFN(item.getInvoiceTFN());

            orderRepository.save(order);

            OrderDetail detail = new OrderDetail();
            detail.setSku(item.getSku());
            detail.setUnitPrice(item.getSku().getGroupBookingPrice());
            detail.setProductNo(item.getGroupBooking().getProductNo());
            detail.setDefaultImage(item.getGroupBooking().getDefaultImage());
            detail.setGoodsName(item.getGroupBooking().getGoodsName());
            detail.setSpecs(item.getSpecs());
            detail.setQuantity(item.getQuantity());
            detail.setPrice(item.getPrice());
            detail.setNote(item.getNote());
            detail.setOrder(order);
            detail.setMarketingType(2);

            detailRepository.save(detail);


        }

    }

    /**
     * 提交预售订单
     */
    public Order submitPresellOrder(WebUser member, OrderDTO orderDTO) {

        GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(orderDTO.getDetails().get(0).getId()), GoodsSku.class);
        WebUser merchant = queryChannelService.findOne(QWebUser.webUser.id.eq(sku.getMerchant().getId()), WebUser.class);

        Order order = new Order();
        order.setMember(member);
        order.setMerchant(merchant);
        order.setCreateTime(new Timestamp(System.currentTimeMillis()));
        order.setDeliveryName(orderDTO.getDeliveryName());
        order.setDeliveryProvince(orderDTO.getDeliveryProvince());
        order.setDeliveryCity(orderDTO.getDeliveryCity());
        order.setDeliveryArea(orderDTO.getDeliveryArea());
        order.setDeliveryAddress(orderDTO.getDeliveryAddress());
        order.setDeliveryMobile(orderDTO.getDeliveryMobile());
        order.setShippingMethod(orderDTO.getShippingMethod());
        order.setGoodsQuantity(orderDTO.getDetails().get(0).getQuantity());

        String orderNo = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + merchant.getId() + member.getId();
        order.setOrderNo(orderNo);

        order.setStatus(1);
        order.setPayStatus(2);
        order.setMarketingType(5);

        order.setInvoiceTFN(orderDTO.getInvoiceTFN());
        order.setInvoiceTitle(orderDTO.getInvoiceTitle());
        order.setHaveInvoice(orderDTO.getHaveInvoice());
        order.setInvoiceTitleType(orderDTO.getInvoiceTitleType());
        order.setInvoiceType(orderDTO.getInvoiceType());
        orderRepository.save(order);


        double freightPrice = 0;
        int quantity = orderDTO.getDetails().get(0).getQuantity();

        //订单总价（不包运费）
        double subtotalPrice = ArithUtils.mul(ArithUtils.add(sku.getPresellSubscription(), sku.getPresellRetainage()), orderDTO.getDetails().get(0).getQuantity());     //单价 * 数量

        if (subtotalPrice < 0) {
            subtotalPrice = 0;
        }

        //运费计算
        OrderDetail detail = new OrderDetail();

        detail.setSku(sku);
        detail.setUnitPrice(sku.getPresellPrice());
        detail.setProductNo(sku.getGoods().getGoodsNo());
        detail.setDefaultImage(sku.getGoods().getDefaultImage());
        detail.setGoodsName(sku.getGoods().getName());
        detail.setSpecs(sku.getAttribute1().getName() + " " + (null != sku.getAttribute2() ? sku.getAttribute2().getName() : ""));
        detail.setQuantity(orderDTO.getDetails().get(0).getQuantity());
        detail.setPrice(subtotalPrice);
        detail.setOrder(order);
        detail.setMarketingType(5);

        detailRepository.save(detail);
        Goods goods = sku.getGoods();


        if (detail.getSku().getGoods().getPostageType() == 1) {     //走运费模板

            MerchantFreight freight = queryChannelService.findOne(QMerchantFreight.merchantFreight.city.eq(order.getDeliveryCity()).and(QMerchantFreight.merchantFreight.merchant.eq(merchant).and(QMerchantFreight.merchantFreight.template.id.eq(goods.getFreightTemplate().getId()))), MerchantFreight.class);

            MerchantFreightTemplate template = queryChannelService.findOne(QMerchantFreightTemplate.merchantFreightTemplate.id.eq(goods.getFreightTemplate().getId()), MerchantFreightTemplate.class);

            //按重量
            if (template.getType() == 1) {

                double gram = ArithUtils.mul(goods.getGram(), orderDTO.getDetails().get(0).getQuantity());//总重量

                if (null != freight) {   //拿到了模板内设置的区域运费
                    if (gram <= freight.getFirstWeight()) {
                        freightPrice = freight.getFirstWeightAmount();
                    } else {
                        freightPrice = ArithUtils.add(freight.getFirstWeightAmount(), ArithUtils.mul(ArithUtils.div(ArithUtils.sub(gram, freight.getFirstWeight()), freight.getOtherWeight(), 2), freight.getOtherWeightAmount()));
                    }
                } else {
                    if (gram <= template.getDefaultWeight()) {
                        freightPrice = template.getDefaultWeightAmount();
                    } else {
                        freightPrice = ArithUtils.add(template.getDefaultWeightAmount(), ArithUtils.mul(ArithUtils.div(ArithUtils.sub(gram, template.getDefaultWeight()), template.getDefaultAddWeight(), 2), template.getDefaultAddWeightAmount()));
                    }
                }
            }

            //按件
            if (template.getType() == 2) {

                if (null != freight) {

                    if (orderDTO.getDetails().get(0).getQuantity() <= freight.getFirstPiece()) {
                        freightPrice = freight.getFirstPieceAmount();
                    } else {
                        freightPrice = ArithUtils.add(freight.getFirstPieceAmount(), ArithUtils.mul(ArithUtils.sub(orderDTO.getDetails().get(0).getQuantity(), freight.getFirstPiece()), freight.getOtherPieceAmount()));
                    }

                } else {

                    if (orderDTO.getDetails().get(0).getQuantity() <= template.getDefaultPiece()) {
                        freightPrice = template.getDefaultPieceAmount();
                    } else {
                        freightPrice = ArithUtils.add(template.getDefaultPieceAmount(), ArithUtils.mul(ArithUtils.sub(orderDTO.getDetails().get(0).getQuantity(), template.getDefaultPiece()), template.getDefaultAddPieceAmount()));
                    }

                }

            }


        } else if (detail.getSku().getGoods().getPostageType() == 2) {      //包邮
            freightPrice = ArithUtils.add(freightPrice, 0);

        } else if (detail.getSku().getGoods().getPostageType() == 3) {       //指定运费
            freightPrice = ArithUtils.add(freightPrice, ArithUtils.mul(detail.getSku().getGoods().getPostage(), orderDTO.getDetails().get(0).getQuantity()));
        }

        if (order.getShippingMethod() == 2) {
            freightPrice = 0;
            order.setShippingAddress(order.getMerchant().getWarehouseAddress());
        }

        double totalPrice = ArithUtils.add(freightPrice, subtotalPrice);

        order.setFreightPrice(freightPrice);
        order.setGoodsSubtotalPrice(subtotalPrice);

        order.setPrice(totalPrice);
        order.setMoney(totalPrice);
        order.setGoodsQuantity(quantity);
        order.setPrepaidDepositPrice(ArithUtils.mul(sku.getPresellSubscription(), quantity));
        order.setFinalPaymentPrice(ArithUtils.add(ArithUtils.mul(sku.getPresellRetainage(), quantity), freightPrice));

        LocalDateTime dateTime = LocalDateTime.now().plusHours(1);
        order.setAutoCancelTime(Timestamp.valueOf(dateTime));

        orderRepository.save(order);

        //减库存，加销量
        sku = queryChannelService.findOne(QGoodsSku.goodsSku.eq(detail.getSku()), GoodsSku.class);
        Requires.isTrue(sku.getStore() > detail.getQuantity(), "库存不足,无法下单");

        sku.setStore(Math.max((sku.getStore() - detail.getQuantity()), 0));
        skuRepository.save(sku);

        goods = queryChannelService.findOne(QGoods.goods.eq(sku.getGoods()), Goods.class);
        goods.setStore(Math.max((goods.getStore() - detail.getQuantity()), 0));
        goods.setSalesVolume(goods.getSalesVolume() + detail.getQuantity());
        goods.setPresellSalesVolume(goods.getPresellSalesVolume() + detail.getQuantity());

        if (goods.getStore() == 0) {
            goods.setStatus(6);
        }

        goodsRepository.save(goods);

        return order;

    }

    /**
     * 预售订单定金支付成功
     */
    public void presellSubscriptionOrderWechatPaySuccess(Order order) {
        order.setPayMethod(1);
        order.setPayStatus(3);
        order.setStatus(7);
        order.setPresellSubscriptionPayTime(new Timestamp(System.currentTimeMillis()));
        orderRepository.save(order);
    }

    /**
     * 微信支付预售订单定金支付
     */
    public void presellSubscriptionWechatPay(String payNo, Order order) {
        order.setPresellSubscriptionPayNo(payNo);
        order.setPayMethod(1);
        orderRepository.save(order);
    }

    /**
     * 微信支付预售订单尾款支付
     */
    public void presellRetainageWechatPay(String payNo, Order order) {
        order.setPresellRetainagePayNo(payNo);
        order.setPayMethod(1);
        orderRepository.save(order);
    }

    /**
     * 预售订单尾款支付成功
     */
    public void presellRetainageOrderWechatPaySuccess(Order order) {
        order.setPayStatus(1);
        order.setStatus(2);
        order.setPresellRetainagePayTime(new Timestamp(System.currentTimeMillis()));
        order.setPayTime(new Timestamp(System.currentTimeMillis()));
        orderRepository.save(order);
    }

    /**
     * 购物卡支付(当购物卡完全抵消订单金额的时候)
     */
    public void shoppingCardPaySuccess(List<Order> orders) {
        for (Order order : orders) {
            order.setPayStatus(1);
            order.setPayMethod(4);
            order.setPayTime(new Timestamp(System.currentTimeMillis()));
            order.setStatus(2);


            //赠品活动订单，给赠品减库存
            if (order.getMarketingType() == 1) {

                List<Goods> giftGoodses = queryChannelService.findAll("select g.goods from GiftGoods g where g.gift.id = :id ", ImmutableMap.of("id", order.getGiftActivity().getId()), Goods.class);

                for (Goods giftGoodse : giftGoodses) {
                    giftGoodse.setStore(giftGoodse.getStore() - 1 == 0 ? 0 : giftGoodse.getStore() - 1);
                    giftGoodse.setSalesVolume(giftGoodse.getSalesVolume() + 1);
                    goodsRepository.save(giftGoodse);

                    GoodsSku sku = giftGoodse.getSkus().get(0);
                    sku.setStore(sku.getStore() - 1);
                    skuRepository.save(sku);
                }

            }


        }
        orderRepository.save(orders);
    }

    /**
     * 取消拼团订单
     */
    public void cancelGroupBooking(GroupBookingOrder order) throws Exception {
        order.setStatus(5);
        groupBookingOrderRepository.save(order);

        GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(order.getSku().getId()), GoodsSku.class);
        //加库存，减销量
        sku.setGroupBookingStore(sku.getGroupBookingStore() + order.getQuantity());
        sku.setStore(sku.getStore() + order.getQuantity());
        skuRepository.save(sku);

        Goods goods = queryChannelService.findOne(QGoods.goods.eq(sku.getGoods()), Goods.class);
        goods.setGroupBookingStore(goods.getGroupBookingStore() + order.getQuantity());
        goods.setGroupBookingSalesVolume(goods.getGroupBookingSalesVolume() - order.getQuantity());
        goods.setStore(goods.getStore() + order.getQuantity());
        goods.setSalesVolume(goods.getSalesVolume() - order.getQuantity());

        if (goods.getGroupBookingStatus() == 6 && new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(goods.getGroupBookingEndTime()).getTime() >= new Date().getTime()) {
            goods.setGroupBookingStatus(5);
        }

        goodsRepository.save(goods);

    }

    /**
     * 商家使用余额组合微信支付采购订单
     */
    public void blanceOrderPay(String payNo, Order order) {

        WebUser merchant = queryChannelService.findOne(QWebUser.webUser.id.eq(order.getMember().getId()), WebUser.class);
        order.setPayMethod(3);
        order.setPayNo(payNo);
        order.setBlancePrice(merchant.getBalance());

        orderRepository.save(order);

        if (order.getDeliveryType() == 2) {
            List<OrderDetail> details = order.getDetails();
            for (OrderDetail detail : details) {
                if (detail.getQuantity() - detail.getDeliveryQuantity() > 0) {

                    CloudStoreGoods cloudStoreGoods = new CloudStoreGoods();
                    cloudStoreGoods.setMerchant(order.getMember());
                    cloudStoreGoods.setSupplier(order.getMerchant());
                    cloudStoreGoods.setQuantity(detail.getQuantity() - detail.getDeliveryQuantity());
                    cloudStoreGoods.setGoods(detail.getSku().getGoods());
                    cloudStoreGoods.setSku(detail.getSku());
                    cloudStoreGoods.setStatus(1);
                    cloudStoreGoods.setCreateTime(new Timestamp(System.currentTimeMillis()));

                    cloudStoreRepository.save(cloudStoreGoods);

                }
            }
        }

    }

    /**
     * 商家申请线下银行卡转账支付（采购端）
     */
    public void bankCardPay(Order order) {
        order.setPayMethod(5);
        order.setStatus(9);

        orderRepository.save(order);
    }

    /**
     * 线下转账审核
     */
    public void processBankCardPay(Order params) {

        Order order = queryChannelService.findOne(QOrder.order.id.eq(params.getId()), Order.class);
        order.setStatus(params.getStatus());
        orderRepository.save(order);

        if (order.getStatus() == 6) {

            //减销量，加库存
            for (OrderDetail detail : order.getDetails()) {
                GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(detail.getSku().getId()), GoodsSku.class);
                sku.setStore(sku.getStore() + detail.getQuantity());
                skuRepository.save(sku);

                Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(sku.getGoods().getId()), Goods.class);
                goods.setStore(goods.getStore() + detail.getQuantity());
                goods.setSalesVolume(goods.getSalesVolume() - detail.getQuantity());
                goodsRepository.save(goods);
            }

        }

        if (order.getStatus() == 2 && order.getDeliveryType() == 2) {
            List<OrderDetail> details = order.getDetails();
            for (OrderDetail detail : details) {
                if (detail.getQuantity() - detail.getDeliveryQuantity() > 0) {

                    CloudStoreGoods cloudStoreGoods = new CloudStoreGoods();
                    cloudStoreGoods.setMerchant(order.getMember());
                    cloudStoreGoods.setSupplier(order.getMerchant());
                    cloudStoreGoods.setQuantity(detail.getQuantity() - detail.getDeliveryQuantity());
                    cloudStoreGoods.setGoods(detail.getSku().getGoods());
                    cloudStoreGoods.setSku(detail.getSku());
                    cloudStoreGoods.setStatus(1);
                    cloudStoreGoods.setCreateTime(new Timestamp(System.currentTimeMillis()));

                    cloudStoreRepository.save(cloudStoreGoods);

                }
            }
        }

    }

    /**
     * 商家采购供应商商品订单使用钱包余额全量抵扣支付
     */
    public void blanceFullPay(List<Order> orders) {

        for (Order order : orders) {

            WebUser merchant = queryChannelService.findOne(QWebUser.webUser.id.eq(order.getMember().getId()), WebUser.class);

            merchant.setBalance(ArithUtils.sub(merchant.getBalance(), order.getPrice()));
            userRepository.save(merchant);


            order.setIsBlanceOrder(1);
            order.setBlancePrice(order.getPrice());
            order.setPayMethod(6);
            order.setPayTime(new Timestamp(System.currentTimeMillis()));
            order.setPayStatus(1);
            order.setStatus(2);

            orderRepository.save(order);

            TradingLog tradingLog = new TradingLog();
            tradingLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
            tradingLog.setMerchant(merchant);
            tradingLog.setStatus(0);
            tradingLog.setType(2);
            tradingLog.setAmount(order.getPrice());
            tradingLog.setOrderNo(order.getOrderNo());
            tradingLogRepository.save(tradingLog);

            if (order.getDeliveryType() == 2) {
                List<OrderDetail> details = order.getDetails();
                for (OrderDetail detail : details) {
                    if (detail.getQuantity() - detail.getDeliveryQuantity() > 0) {

                        CloudStoreGoods cloudStoreGoods = new CloudStoreGoods();
                        cloudStoreGoods.setMerchant(order.getMember());
                        cloudStoreGoods.setSupplier(order.getMerchant());
                        cloudStoreGoods.setQuantity(detail.getQuantity() - detail.getDeliveryQuantity());
                        cloudStoreGoods.setGoods(detail.getSku().getGoods());
                        cloudStoreGoods.setSku(detail.getSku());
                        cloudStoreGoods.setStatus(1);
                        cloudStoreGoods.setCreateTime(new Timestamp(System.currentTimeMillis()));

                        cloudStoreRepository.save(cloudStoreGoods);

                    }
                }
            }

        }


    }

    /**
     * 采购订单发货
     */
    public void purchaseOrderDelivery(Order params) {

        Order order = queryChannelService.findOne(QOrder.order.id.eq(params.getId()), Order.class);

        SupplierOrderDelivery delivery = new SupplierOrderDelivery();
        delivery.setCreateTime(new Timestamp(System.currentTimeMillis()));

        Express express = queryChannelService.findOne(QExpress.express.expressCompanyCode.eq(params.getExpressCode()), Express.class);

        delivery.setExpressCompany(express.getName());
        delivery.setExpressCompanyCode(express.getExpressCompanyCode());
        delivery.setExpressNo(params.getExpressesNo());
        delivery.setOrder(order);
        deliveryRepository.save(delivery);

        List<String> items = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(params.getData());
        for (String item : items) {
            int deliveryQuantity = Integer.parseInt(item.substring(item.indexOf(":") + 1));
            if (deliveryQuantity <= 0) {
                continue;
            }
            OrderDetail detail = queryChannelService.findOne(QOrderDetail.orderDetail.id.eq(Long.valueOf(item.substring(0, item.indexOf(":")))), OrderDetail.class);

            SupplierOrderDeliveryDetail deliveryDetail = new SupplierOrderDeliveryDetail();
            deliveryDetail.setOrderDetail(detail);
            deliveryDetail.setDeliveryQuantity(deliveryQuantity);
            deliveryDetail.setDelivery(delivery);
            deliveryDetailRepository.save(deliveryDetail);

            detail.setShippedQuantity(detail.getShippedQuantity() + deliveryQuantity);

            if (detail.getShippedQuantity() >= detail.getDeliveryQuantity()) {
                detail.setFinishNeedDeliveryStatus(1);
            }

            detailRepository.save(detail);


        }

        List<OrderDetail> details = queryChannelService.findAll(QOrderDetail.orderDetail.order.eq(order), OrderDetail.class);

        boolean allFinishStatus = true;

        for (OrderDetail detail : details) {
            if (detail.getFinishNeedDeliveryStatus() != 1) {
                allFinishStatus = false;
                break;
            }
        }

        if (allFinishStatus) {
            order.setStatus(3);
        } else {
            order.setStatus(10);
        }

        order.setExpressCompany(express.getName());
        order.setExpressesNo(params.getExpressesNo());
        order.setExpressCode(express.getExpressCompanyCode());

        order.setDeliveryTime(new Timestamp(System.currentTimeMillis()));
        orderRepository.save(order);

        Message message = new Message();
        message.setType(2);
        message.setMember(order.getMember());
        message.setOrderId(order.getId());
        message.setTitle("您有1笔订单已发货");
        message.setDigest("订单号:" + order.getOrderNo());
        message.setCreateTime(order.getDeliveryTime());

        if (order.getIsSupplier() == 1) {
            message.setPlatformType(1);
        }

        messageRepository.save(message);

        try {
            AliYunSmsService.send(order.getMember().getMobile(),
                    PropertiesHelps.getValue("sign_name2"),
                    "SMS_211020801",
                    ImmutableMap.of("merchantName", order.getMerchant().getUsername())
            );
        } catch (Exception e) {
            log.error("发送短信验证码异常", e);
        }

    }


    public void wechatAppPay(String payNo, Order order) {
        order.setPayNo(payNo);
        order.setPayMethod(1);
        order.setAppPay(1);
        orderRepository.save(order);
    }

    public void alipayAppPay(String payNo, Order order) {
        order.setPayNo(payNo);
        order.setPayMethod(2);
        order.setAppPay(1);
        orderRepository.save(order);
    }

    public void wechatAppPayGroupBooking(String payNo, GroupBookingOrder order) {
        order.setPayNo(payNo);
        order.setPayMethod(1);
        order.setAppPay(1);
        groupBookingOrderRepository.save(order);
    }

    public void alipayAppPayGroupBooking(String payNo, GroupBookingOrder order) {
        order.setPayNo(payNo);
        order.setPayMethod(2);
        order.setAppPay(1);
        groupBookingOrderRepository.save(order);
    }

    public void presellSubscriptionWechatAppPay(String payNo, Order order) {
        order.setPresellSubscriptionPayNo(payNo);
        order.setPayMethod(1);
        order.setAppPay(1);
        orderRepository.save(order);
    }

    public void presellSubscriptionAlipayAppPay(String payNo, Order order) {
        order.setPresellSubscriptionPayNo(payNo);
        order.setPayMethod(2);
        order.setAppPay(1);
        orderRepository.save(order);
    }

    public void presellRetainageWechatAppPay(String payNo, Order order) {
        order.setPresellRetainagePayNo(payNo);
        order.setPayMethod(1);
        order.setAppPay(1);
        orderRepository.save(order);
    }

    public void presellRetainageAlipayAppPay(String payNo, Order order) {
        order.setPresellRetainagePayNo(payNo);
        order.setPayMethod(2);
        order.setAppPay(1);
        orderRepository.save(order);
    }

}